Declaring variable types
August 14, 2023
Today I’ll be love coding again. I hope you can join me! I’ll be working on the backlog for my open-source CouchDB SDK, https://kivik.io/. First some light refactoring, then adding a long-missing feature. Join me to see how many mistakes a senior Go dev makes while coding.
We ended last week with a look at variable declarations. Today we continue that, with a look at how a variable’s type is determined. This can be a bit subtle.
Variable declarations
…
If a type is present, each variable is given that type. Otherwise, each variable is given the type of the corresponding initialization value in the assignment. If that value is an untyped constant, it is first implicitly converted to its default type; if it is an untyped boolean value, it is first implicitly converted to type
bool
. The predeclared valuenil
cannot be used to initialize a variable with no explicit type.var d = math.Sin(0.5) // d is float64 var i = 42 // i is int var t, ok = x.(T) // t is T, ok is bool var n = nil // illegal
Let’s look at some examples, from most to least specific, to try to make this as clear as possible.
// Variable type provided explicitly
var int x = 3 // x is of type `int`, and has a value of 3
var int y // y is of type `int`, and gets the zero value for int, which is 0
// Variable type omitted
var z = int(7) // Type is provided in the corresponding initialization value (int)
const MaxItems = 100
var a = MaxItems // Variable assigned to untyped constant gets default type (int)
var b = nil // illegal, no default type can be determined
type Person struct {
Name string
}
var *Person b = nil // Legal, the type is known, and can be nil
Quotes from The Go Programming Language Specification Version of August 2, 2023