Golang: Variables

By Xah Lee. Date: . Last updated: .

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

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

// 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)
        // 0 0 false ""


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

Golang Topics

  1. Compile, Run
  2. Package, Import
  3. Function
  4. Variable
  5. Constant
  6. If Then Else
  7. switch/case
  8. Loop
  9. Basic Types
  10. Array
  11. Slice
  12. map

If you have a question, put $5 at patreon and message me.