Golang: Variables

By Xah Lee. Date: . Last updated: .

var declares one or more variables. Put the variable's type at the end.

package main

// package level variable
var c, d, e int

func main() {
}

// 0 0 0 0
package main

import "fmt"

func main() {
        // function level variable
        var b int
        fmt.Println(b)
}

// 0
package main

import "fmt"

// package level variable
var c, d, e int

func main() {
        // function level variable
        var i int
        fmt.Println(i, c, d, e)
}

// 0 0 0 0

Variables with 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.

package main

import "fmt"

var i, j = 3, "no"

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

// 3 no

Variable Syntax Shortcut

Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.

package main

import "fmt"

func main() {
        k := 3
        fmt.Println(k)
}

// 3

Initial Value, Zero Values

Variables declared without an explicit initial value are given their zero value.

The zero value is:

package main

import "fmt"

func main() {
        var i int
        var f float64
        var b bool
        var s string
        fmt.Printf("%v %v %v %q\n", i, f, b, s)
}

Reference

The Go Programming Language Specification - The Go Programming Language#Variables