Basics
The `var` statement declares a list of variables. Type is last. A `var` statement can be at package or function level. Use var when you to set a variable type but don’t want to set the variable value yet.
This also works with interfaces.
Initializers
A var declaration can include initializers, one per variable. If an initializer is present, the type can be omitted; the variable will take the type of the initializer.
Short variable declarations
Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type. Outside a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available.
Basic types
Go’s basic types are
bool
string
int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr
byte // alias for uint8
rune // alias for int32 // represents a Unicode code point
float32 float64
complex64 complex128
The example shows variables of several types, and also that variable declarations may be “factored” into blocks, as with import statements.
The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems. When you need an integer value you should use int unless you have a specific reason to use a sized or unsigned integer type.
Zero values
Variables declared without an explicit initial value are given their zero value.
The zero value is:
- 0 for numeric types
- false for the boolean type
- "" for strings
Type conversions
The expression `T(v)` converts the value v to the type T.
Type inference
When declaring a variable without specifying an explicit type (either by using the := syntax or var = expression syntax), the variable’s type is inferred from the value on the right hand side.
When the right hand side of the declaration is typed, the new variable is of that same type:
But when the right hand side contains an untyped numeric constant, the new variable may be an int, float64, or complex128 depending on the precision of the constant:
Constants
Constants are declared like variables, but with the const keyword.
Constants can be character, string, boolean, or numeric values.
Constants cannot be declared using the := syntax.