The Go Language (PART-8)


Variables


A var declaration creates a variable of a particular type, attaches a name to it, and sets its initial value. Each declaration has the general form

  1. Creates a variable of a particular type,

  2. Attaches a name to it,

  3. Sets its initial value



var name type = expression

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. If the expression is omitted, the initial value is the zero value for the type, which is 0 for numbers, false for booleans, "" for strings, and nil for interfaces and reference types (slice, pointer, map, channel, function). 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; in Go there is no such thing as an uninitialized variable.

In Go there is no such thing as an uninitialized variable.

This simplifies code and often ensures sensible behavior of boundary conditions without extra work. For example,

var s string
fmt.Println(s) // ""

prints an empty string, rather than causing some kind of error or unpredictable behavior. Go programmers often go to some effort to make the zero value of a more complicated type meaningful, so that variables begin life in a useful state.


It is possible to declare and optionally initialize a set of variables in a single declaration, with a matching list of expressions. Omitting the type allows declaration of multiple variables of different types:

var i, j, k int                 // int, int, int
var b, f, s = true, 2.3, "four" // bool, float64, string

Initializers may be literal values or arbitrary expressions. Package-level variables are initialized before main begins and local variables are initialized as their declarations are encountered during function execution.


A set of variables can also be initialized by calling a function that returns multiple values:

var f, err = os.Open(name) // os.Open returns a file and an error


Short variable declarations


Within a function, an alternate form called a short variable declaration may be used to declare and initialize local variables. It takes the form name:=expression, and the type of name is determined by the type of expression.

name := expression

Because of their brevity and flexibility, short variable declarations are used to declare and initialize the majority of local variables. A var declaration tends to be reserved for local variables that need an explicit type that differs from that of the initializer expression, or for when the variable will be assigned a value later and its initial value is unimportant.

i := 100                  // an int
var boiling float64 = 100 // a float64
11 views0 comments

Recent Posts

See All