About
Articles Related
Management
Declaration
Statement
var name type = expression
// Expression can be a function (os.Open returns a file and an error)
var f, err = os.Open( name)
// var is used to specify explicitly the type (erase the default type)
i := 100 // an int
var boiling float64 = 100 // a float64
Either the type or the = expression part may be omitted, but not both.
If:
- the type is omitted, it is determined by the initializer expression.
- the expression is omitted, the initial value is the zero_value for the type
Initialization Time
- Package-level variables are initialized before main begins
- Local variables are initialized as their declarations are encountered during function execution.
Zero-value
A variable can be initialized as part of its declaration. If it is not explicitly initialized, it is implicitly initialized to the zero value for its type which is:
- 0 for numbers,
- false for booleans,
- “” for strings,
- and nil for interfaces and reference types.
The zero value of an aggregate type like an array or a struct has the zero value of all of its elements or fields.
The zero-value mechanism ensures that a variable always holds a well-defined value of its type; This simplifies code and often ensures sensible behavior of boundary conditions without extra work. For example, the below code prints an empty string, rather than causing some kind of error or unpredictable behavior.
var s string
fmt.Println( s) // ""
Assignment
- Tuple assignment
i, j = j, i // swap values of i and j
Blank identifier (Special variable)
The blank identifier (_ ie an underscore) may be used whenever syntax requires a variable name but program logic does not.
Scope, naming and Lifetime
See Go - Name