Go - Variable

Card Puncher Data Processing

About

Language - (Variable | Field) in Go

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:

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

Documentation / Reference





Discover More
Card Puncher Data Processing
Go - New

The expression new(T): creates an unnamed variable of type T, initializes it to the zero value of T, and returns its address, which is a value of type T. new is a predeclared function, not a...



Share this page:
Follow us:
Task Runner