Variable types

February 8, 2023

Variables

The static type (or just type) of a variable is the type given in its declaration, the type provided in the new call or composite literal, or the type of an element of a structured variable.

And here we are at one of the core features of Go, it’s static type system.

Each variable has a specific static type, which is typically provided in the variable definition, although there are a few cases where the type can be inferred.

Let’s look at some explicit examples:

var x int        // x is of type `int`, and is is initialized to the zero value for int
var y int = 123  // y is of type `int`, and initialized to the value 123
var z = int(123) // Alternative form of previous line

And a few examples of inferred types:

type Person struct {
	ID   int
	Name string
}

var p = Person{ID: 123, Name: "Bob"} // p is of type Person, the type of the
                                     // composite literal

var name = p.Name // name is of type string, inferred from the referenced
                  // structured element, Person.Name

A couple of other examples, not directly called out in this part of the spec, where the type can be inferred:

func foo() int { return 3 }

var x = foo() // x is of type int, as that is the type returned by foo()
const x = 123

y = x // y is of type `int`, the default type of an integer constant literal.

Quotes from The Go Programming Language Specification, Version of January 19, 2023


Share this

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

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe