Join me later today for my second Boldly Go Live stream!
Declarations and scope
…
- The scope of an identifier denoting a method receiver, function parameter, or result variable is the function body.
This is pretty intuitive. When declaring a function or method:
func sum(a, b int) (result int) {
/* ... */
}
func (a Animal) Speak() {
/* ... */
}
The scope of any variables mentioned in the function signature (method receiver, function parameter, or result variables), are the function body. In other words, you cannot access those variables outside of the function.
func foo(a int) {
/* ... */
}
var x = a // invalid: a not declared in this scope, only in the body of foo()
Quotes from The Go Programming Language Specification Version of December 15, 2022