go - Golang function contains anonymous scope -


can give me explanation when , why use anonymous scope inside function? (i'm not sure it's called).

i've been given legacy code maintain , of functions contain "scope" have not seen before:

(simplified demonstration purposes)

func dosomething(someboolvalue bool) string {     if someboolvalue {         // stuff         return "yes"     }     {         // weird scope code     }     return "no" } 

i have created go playground demonstrate actual code (that throws error).

it called variable scoping , shadowing:

go lexically scoped using blocks:

1-the scope of predeclared identifier universe block.
2-the scope of identifier denoting constant, type, variable, or function (but not method) declared @ top level (outside function) package block.
3-the scope of package name of imported package file block of file containing import declaration.
4-the scope of identifier denoting method receiver, function parameter, or result variable function body.
5-the scope of constant or variable identifier declared inside function begins @ end of constspec or varspec (shortvardecl short variable declarations) , ends @ end of innermost containing block.
6-the scope of type identifier declared inside function begins @ identifier in typespec , ends @ end of innermost containing block. identifier declared in block may redeclared in inner block. while identifier of inner declaration in scope, denotes entity declared inner declaration.

the package clause not declaration; package name not appear in scope. purpose identify files belonging same package , specify default package name import declarations.

your working sample code:

package main  import (     "fmt" )  func main() {     := 10     {         := 1         fmt.println(i)  // 1     }     fmt.println(i)  // 10 } 

output:

1 10 

and see: where can use variable scoping , shadowing in go?


Comments