Variables

  • In Go, we have to declare a variable before we can use it. This is required and necessary for the compile time safety.
  • Variables are not created at compile time. They are created at run time.
  • The unnamed variables are pointers (like in C).
  • Once we declare a type for a variable, it cannot be changed later. It is static.

Declaring with var

The var statement declares a list of variables with the type declared last.

var (
    name     string
    age      int
    location string
)

Or even

var (
    name, location  string
    age             int
)

Variables can also be declared one by one:

var name     string
var age      int
var location string

A var declaration can include initializers, one per variable.

var (
    name     string = "Prince Oberyn"
    age      int    =  32
    location string = "Dorne"
)

If an initializer is present, the type can be omitted, the variable will take the type of the initializer (inferred typing).

var (
    name     = "Prince Oberyn"
    age      =  32
    location = "Dorne"
)

You can also initialize variables on the same line:

var (
    name, location, age = "Prince Oberyn", "Dorne", 32
)

Short declaration with type inference

Short variable declaration is a very convenient manner of “declaring variable” in Go:

i := 10

It is shorthand of following (Please notice there is no type):

var i = 10

The Go compiler will infer the type according to the value of variable. It is a very handy feature, but on the other side of coin, it also brings some pitfalls which you should pay attention to:

  • With Type Inference, Go can figure out variable type based off it’s assigned value.
  • In Short Declaration, we can declare variable by completely ommitting var keyword along with it’s variable type.
  • It declares and initializes the variable.

Multiple short declaration

  • We can declare and initialize multiple variables of different types using short declaration syntax:
package main

main() {
    someFlag, age, name := true, 30, "किंशुक" // Multiple variables of different types.
}
  • In this type of declaration, number of values and number of names must be the same. Otherwise it will result in error.

Redeclarations With Short Declarations

  • Short Declaration can initialize new variables and assign to existing variables at the same time.

  • At least one of the variable in Short Declaration Redeclaration must be a new variable.

  • For e.g.

  • package main
    
    main() {
        var someFlag bool
    
        // someFlag := true // Error! At least one variable must be new to make this work.
        someFlag, age := true, 30 // This works! Because 'age' is a new variable being declared in the same statement. someFlag will be set (redeclared) to true.
    }
    

Blank Identifier

“There are only two hard things in Computer Science: cache invalidation and naming things”. Tim Bray quoting Phil Karlton

  • Go doesn’t allow unused variables in blocked scope.
  • To ignore a variable, Blank Identifier (_) is used as a variable name in Go.
  • Go compiler will not throw unsed variable error if a blocked scope variable is named _.
  • We cannot use value assigned to _.
  • It is like a black hole that swallows variable.
  • Detailed information and usage of Blank Identifier

Note the rules

(1) This format can only be used in functions

For eg. this will not work:

package main

i := 10

func main() {
  fmt.Println(i)
}

The compiler will complain the following words:

syntax error: non-declaration statement outside function body

  • We cannot use Short Declaration syntax to declare variables in Package Scope.

  • At Package Scope, all declarations should start with a keyword. Since Short Declaration syntax doesn’t have any keyword in it, it doesn’t work at Package Scope.

  • For e.g.

    package main
    
    main() {
        someFlag := true // 'var' keyword and 'variable type' is not specified. It works!
    }
    

A variable can contain any type, including functions:

    action := func() {
        //doing something
    }
    action()

(2) You must declare at least 1 new variable

package main

import "fmt"

func main() {
    var i = 1

    i, err := 2, true

    fmt.Println(i, err)
}

In i, err := 2, false statement, only err is a new declared variable, var is actually declared in var i = 1.

(3) The short variable declaration can shadow the global variable declaration

This may not be what you want, and gives you a big surprise:

package main

import "fmt"

var i = 1

func main() {

    i, err := 2, true

    fmt.Println(i, err)
}

i, err := 2, true actually declares a new local i which makes the global i inaccessible in main function. To use the global variable but not introducing a new local one, one solution maybe like this:

package main

import "fmt"

var i int

func main() {

    var err bool

    i, err = 2, true

    fmt.Println(i, err)
}

Short variable declarations.

References


See also