Why does the compiler complain about an unused variable in this instance (when it is used by fmt.Fprintf)?











up vote
0
down vote

favorite












I have a simple piece of code where I want to convert elements of a slice into json and then print them out to my http.responseWriter.



for _, element := range customers {
result, _ := json.Marshal(element)
fmt.Fprintf(w, string(result))
}


However when I compile this I get the error "result declared and not used". If I add a simple line:



_ = result


Then everything compiles and works fine. Why does the compiler complain about this usage, and what is the correct way to do this in go?



Any insight is appreciated, my searches so far seem to indicate the call to Fprintf should count as a usage.










share|improve this question




















  • 4




    The code you posted does not result in the error you get. For proof, see: Go Playground. Please post a Minimal, Complete, and Verifiable example.
    – icza
    Nov 7 at 22:28








  • 8




    Most likely you have a result variable outside of the for loop, and since you use short variable declaration, that shadows the outer result, and most likely the outer result is the one that is never used, like in this example: Go Playground.
    – icza
    Nov 7 at 22:30












  • Thanks @icza, that was it exactly. I didn't clock how variable declaration was working in go and it was the variable declared outside the scope that was causing the problem. Thanks!
    – Chris
    Nov 7 at 23:58






  • 4




    go vet will catch this sort of problem.
    – Michael Hampton
    Nov 8 at 0:16






  • 2




    Don't use a JSON document as a format string. That's going to bite you sooner or later. Use fmt.Fprint (no f), or simply w.Write(result) instead.
    – Peter
    Nov 8 at 7:16















up vote
0
down vote

favorite












I have a simple piece of code where I want to convert elements of a slice into json and then print them out to my http.responseWriter.



for _, element := range customers {
result, _ := json.Marshal(element)
fmt.Fprintf(w, string(result))
}


However when I compile this I get the error "result declared and not used". If I add a simple line:



_ = result


Then everything compiles and works fine. Why does the compiler complain about this usage, and what is the correct way to do this in go?



Any insight is appreciated, my searches so far seem to indicate the call to Fprintf should count as a usage.










share|improve this question




















  • 4




    The code you posted does not result in the error you get. For proof, see: Go Playground. Please post a Minimal, Complete, and Verifiable example.
    – icza
    Nov 7 at 22:28








  • 8




    Most likely you have a result variable outside of the for loop, and since you use short variable declaration, that shadows the outer result, and most likely the outer result is the one that is never used, like in this example: Go Playground.
    – icza
    Nov 7 at 22:30












  • Thanks @icza, that was it exactly. I didn't clock how variable declaration was working in go and it was the variable declared outside the scope that was causing the problem. Thanks!
    – Chris
    Nov 7 at 23:58






  • 4




    go vet will catch this sort of problem.
    – Michael Hampton
    Nov 8 at 0:16






  • 2




    Don't use a JSON document as a format string. That's going to bite you sooner or later. Use fmt.Fprint (no f), or simply w.Write(result) instead.
    – Peter
    Nov 8 at 7:16













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have a simple piece of code where I want to convert elements of a slice into json and then print them out to my http.responseWriter.



for _, element := range customers {
result, _ := json.Marshal(element)
fmt.Fprintf(w, string(result))
}


However when I compile this I get the error "result declared and not used". If I add a simple line:



_ = result


Then everything compiles and works fine. Why does the compiler complain about this usage, and what is the correct way to do this in go?



Any insight is appreciated, my searches so far seem to indicate the call to Fprintf should count as a usage.










share|improve this question















I have a simple piece of code where I want to convert elements of a slice into json and then print them out to my http.responseWriter.



for _, element := range customers {
result, _ := json.Marshal(element)
fmt.Fprintf(w, string(result))
}


However when I compile this I get the error "result declared and not used". If I add a simple line:



_ = result


Then everything compiles and works fine. Why does the compiler complain about this usage, and what is the correct way to do this in go?



Any insight is appreciated, my searches so far seem to indicate the call to Fprintf should count as a usage.







go






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 8 at 8:35









Flimzy

35.7k96395




35.7k96395










asked Nov 7 at 22:24









Chris

2,66721936




2,66721936








  • 4




    The code you posted does not result in the error you get. For proof, see: Go Playground. Please post a Minimal, Complete, and Verifiable example.
    – icza
    Nov 7 at 22:28








  • 8




    Most likely you have a result variable outside of the for loop, and since you use short variable declaration, that shadows the outer result, and most likely the outer result is the one that is never used, like in this example: Go Playground.
    – icza
    Nov 7 at 22:30












  • Thanks @icza, that was it exactly. I didn't clock how variable declaration was working in go and it was the variable declared outside the scope that was causing the problem. Thanks!
    – Chris
    Nov 7 at 23:58






  • 4




    go vet will catch this sort of problem.
    – Michael Hampton
    Nov 8 at 0:16






  • 2




    Don't use a JSON document as a format string. That's going to bite you sooner or later. Use fmt.Fprint (no f), or simply w.Write(result) instead.
    – Peter
    Nov 8 at 7:16














  • 4




    The code you posted does not result in the error you get. For proof, see: Go Playground. Please post a Minimal, Complete, and Verifiable example.
    – icza
    Nov 7 at 22:28








  • 8




    Most likely you have a result variable outside of the for loop, and since you use short variable declaration, that shadows the outer result, and most likely the outer result is the one that is never used, like in this example: Go Playground.
    – icza
    Nov 7 at 22:30












  • Thanks @icza, that was it exactly. I didn't clock how variable declaration was working in go and it was the variable declared outside the scope that was causing the problem. Thanks!
    – Chris
    Nov 7 at 23:58






  • 4




    go vet will catch this sort of problem.
    – Michael Hampton
    Nov 8 at 0:16






  • 2




    Don't use a JSON document as a format string. That's going to bite you sooner or later. Use fmt.Fprint (no f), or simply w.Write(result) instead.
    – Peter
    Nov 8 at 7:16








4




4




The code you posted does not result in the error you get. For proof, see: Go Playground. Please post a Minimal, Complete, and Verifiable example.
– icza
Nov 7 at 22:28






The code you posted does not result in the error you get. For proof, see: Go Playground. Please post a Minimal, Complete, and Verifiable example.
– icza
Nov 7 at 22:28






8




8




Most likely you have a result variable outside of the for loop, and since you use short variable declaration, that shadows the outer result, and most likely the outer result is the one that is never used, like in this example: Go Playground.
– icza
Nov 7 at 22:30






Most likely you have a result variable outside of the for loop, and since you use short variable declaration, that shadows the outer result, and most likely the outer result is the one that is never used, like in this example: Go Playground.
– icza
Nov 7 at 22:30














Thanks @icza, that was it exactly. I didn't clock how variable declaration was working in go and it was the variable declared outside the scope that was causing the problem. Thanks!
– Chris
Nov 7 at 23:58




Thanks @icza, that was it exactly. I didn't clock how variable declaration was working in go and it was the variable declared outside the scope that was causing the problem. Thanks!
– Chris
Nov 7 at 23:58




4




4




go vet will catch this sort of problem.
– Michael Hampton
Nov 8 at 0:16




go vet will catch this sort of problem.
– Michael Hampton
Nov 8 at 0:16




2




2




Don't use a JSON document as a format string. That's going to bite you sooner or later. Use fmt.Fprint (no f), or simply w.Write(result) instead.
– Peter
Nov 8 at 7:16




Don't use a JSON document as a format string. That's going to bite you sooner or later. Use fmt.Fprint (no f), or simply w.Write(result) instead.
– Peter
Nov 8 at 7:16












1 Answer
1






active

oldest

votes

















up vote
2
down vote



accepted










The code in question does not result in the error posted, for proof, check it on the Go Playground.



This error usually is (and the op confirmed it is too in this case) caused by having a local variable with same name outside of the block, and when using the short variable declaration, that shadows that variable.



This error can be reproduced with the following code:



var result byte

customers := int{}
w := os.Stdout

for _, element := range customers {
result, _ := json.Marshal(element)
fmt.Fprintf(w, string(result))
}


Attempting to compile and run it, we get the error (try it on the Go Playground):



prog.go:10:6: result declared and not used


Solution is to use a simple assignment instead of the short variable declaration if intention is to use the existing variable (in which case no new variable will be created), or use a different name for the variable if intention is not to use the outer, existing variable (but then the outer variable is to be removed or be used of course).






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53198800%2fwhy-does-the-compiler-complain-about-an-unused-variable-in-this-instance-when-i%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    2
    down vote



    accepted










    The code in question does not result in the error posted, for proof, check it on the Go Playground.



    This error usually is (and the op confirmed it is too in this case) caused by having a local variable with same name outside of the block, and when using the short variable declaration, that shadows that variable.



    This error can be reproduced with the following code:



    var result byte

    customers := int{}
    w := os.Stdout

    for _, element := range customers {
    result, _ := json.Marshal(element)
    fmt.Fprintf(w, string(result))
    }


    Attempting to compile and run it, we get the error (try it on the Go Playground):



    prog.go:10:6: result declared and not used


    Solution is to use a simple assignment instead of the short variable declaration if intention is to use the existing variable (in which case no new variable will be created), or use a different name for the variable if intention is not to use the outer, existing variable (but then the outer variable is to be removed or be used of course).






    share|improve this answer

























      up vote
      2
      down vote



      accepted










      The code in question does not result in the error posted, for proof, check it on the Go Playground.



      This error usually is (and the op confirmed it is too in this case) caused by having a local variable with same name outside of the block, and when using the short variable declaration, that shadows that variable.



      This error can be reproduced with the following code:



      var result byte

      customers := int{}
      w := os.Stdout

      for _, element := range customers {
      result, _ := json.Marshal(element)
      fmt.Fprintf(w, string(result))
      }


      Attempting to compile and run it, we get the error (try it on the Go Playground):



      prog.go:10:6: result declared and not used


      Solution is to use a simple assignment instead of the short variable declaration if intention is to use the existing variable (in which case no new variable will be created), or use a different name for the variable if intention is not to use the outer, existing variable (but then the outer variable is to be removed or be used of course).






      share|improve this answer























        up vote
        2
        down vote



        accepted







        up vote
        2
        down vote



        accepted






        The code in question does not result in the error posted, for proof, check it on the Go Playground.



        This error usually is (and the op confirmed it is too in this case) caused by having a local variable with same name outside of the block, and when using the short variable declaration, that shadows that variable.



        This error can be reproduced with the following code:



        var result byte

        customers := int{}
        w := os.Stdout

        for _, element := range customers {
        result, _ := json.Marshal(element)
        fmt.Fprintf(w, string(result))
        }


        Attempting to compile and run it, we get the error (try it on the Go Playground):



        prog.go:10:6: result declared and not used


        Solution is to use a simple assignment instead of the short variable declaration if intention is to use the existing variable (in which case no new variable will be created), or use a different name for the variable if intention is not to use the outer, existing variable (but then the outer variable is to be removed or be used of course).






        share|improve this answer












        The code in question does not result in the error posted, for proof, check it on the Go Playground.



        This error usually is (and the op confirmed it is too in this case) caused by having a local variable with same name outside of the block, and when using the short variable declaration, that shadows that variable.



        This error can be reproduced with the following code:



        var result byte

        customers := int{}
        w := os.Stdout

        for _, element := range customers {
        result, _ := json.Marshal(element)
        fmt.Fprintf(w, string(result))
        }


        Attempting to compile and run it, we get the error (try it on the Go Playground):



        prog.go:10:6: result declared and not used


        Solution is to use a simple assignment instead of the short variable declaration if intention is to use the existing variable (in which case no new variable will be created), or use a different name for the variable if intention is not to use the outer, existing variable (but then the outer variable is to be removed or be used of course).







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 8 at 7:42









        icza

        156k22303343




        156k22303343






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53198800%2fwhy-does-the-compiler-complain-about-an-unused-variable-in-this-instance-when-i%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            Popular posts from this blog

            Landwehr

            Reims

            Schenkenzell