-3

Take this incredibly simple example. which shows variable assignment in and out of a block.

On compilation this results in: u declared and not used

var u string
{
    u, err := url.Parse("http://bing.com/search?q=dotnet")
    if err != nil {
        log.Fatal(err)
    }
}
log.Debug(u)

This simulates a logic block during which we might assess several things and set a var to the value we like depending on logic evaluation. How is this possible?

David
  • 34,836
  • 11
  • 47
  • 77
  • 2
    Exactly as is says, the `u` declared inside the block is not used (the actual error will tell you the exact line). There's no magic here, and the error is probably saving you from a bug in your code. – JimB Nov 21 '18 at 16:55
  • 1
    The short variable declaration will create new `u` and `err` variables, because `u` is not declared in the same block. Redeclaration can only happen if the variable was declared in the same block. – icza Nov 21 '18 at 16:57
  • Can't believe nobody used the one sentence that clears everything up: `u, err :=` is a declare and assign of both `u` and `err` inside a block, _masking_ the `var u string` declared in a higher scope. – Elias Van Ootegem Nov 21 '18 at 17:21

1 Answers1

0

Please pay attention that:

u, err := url.Parse("http://bing.com/search?q=dotnet")

in this line of code you have block scoped variable u which is differ from those one which declared in line: var u string, hence you have this error.
Moreover here you have shadowing for variable u from outer block scope which may lead to bugs, see this:

var u string
u = "blank"
{
    u, err := url.Parse("http://bing.com/search?q=dotnet")
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("%#v", u)
}
log.Printf("%#v", u)

Result will be:

2018/11/21 19:12:33 &url.URL{Scheme:"http", Opaque:"", User:(*url.Userinfo)(nil), Host:"bing.com", Path:"/search", RawPath:"", ForceQuery:false, RawQuery:"q=dotnet", Fragment:""}
2018/11/21 19:12:33 "blank"

As you can see here you have even different data types, and variable u not changed after this block.

cn007b
  • 16,596
  • 7
  • 59
  • 74
  • Thanks for the comment. What still seems to escape me a little is how to access the set value of a variable set within a logic block. Take for example a simple - if { u="bob1"}else{ u = "bob2"} log.Printf(u) – David Nov 22 '18 at 09:07