This question already has an answer here:
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?
</div>
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.