Scope of the function block

June 26, 2023

Join me later today for my second Boldly Go Live stream!


Declarations and scope

  1. 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


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


Go statements, conclusion

Today we finish the description of go statements: Go statements … When the function terminates, its goroutine also terminates. If the function has any return values, they are discarded when the function completes. go Server() go func(ch chan<- bool) { for { sleep(10); ch <- true }} (c) Okay, so that bit about discarding return values makes sense, right? func main() { go sum(1, 3) // return value discarded } func sum(a, b int) int { return a + b } But what if you need that return value for something?


Refresher on methods

In yesterday’s email, I failed to include the example included in the spec, which doesn’t make sense to include otherwise. I’ve updated the web version of the email in case you’re super curious to see what I left out. We’ve already covered these details, but they’re logically mentioned again in the section about function calls, so we’ll cover them here: Calls … A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m.


Receiver uniqueness

Today I’ll be love coding again. I hope you can join me! I’ll be continuing where I left off, working on the backlog for my open-source CouchDB SDK, https://kivik.io/. Join me to see how many mistakes a senior Go dev makes while coding. Method declarations … A non-blank receiver identifier must be unique in the method signature. If the receiver’s value is not referenced inside the body of the method, its identifier may be omitted in the declaration.

Get daily content like this in your inbox!

Subscribe