The universe and package blocks

June 22, 2023

Let’s now dive into the specific scoping rules in Go. There are 8 rules here, and we’ll take one or two per day…

Declarations and scope

Go is lexically scoped using blocks:

  1. The scope of a predeclared identifier is the universe block.

The “universe block”, which encompasses all Go source text, only contains the predeclared identifiers defined in the specification. Specifically, these identifiers are the names of predeclared types, the constants true, false, and iota, the zero value nil, and the built-in functions.

That’s it!

You, the programmer, cannot add any declarations to the universe block.

  1. The scope of an identifier denoting a constant, type, variable, or function (but not method) declared at top level (outside any function) is the package block.

The highest level scope where you can add declarations is the package block. You do this by declaring constants(1), types(2), variables(3), and functions(4) in a .go source file, outside of any function.

package foo // Package scope FTW!

const pet = animal("dog") // (1)

type animal string // (2)

var cattle = animal("cow") // (3)

func feed(a animal) { // (4)
}

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 .

Get daily content like this in your inbox!

Subscribe