Go Variable Declarations

Declaring Go variables with var and constants with const

Variables (var)

Use var variableName type to define a variable.

var a1 int

You can specify an initial value when declaring a variable. If you omit it, the variable is initialized with a zero value such as 0 or the empty string "".

var a1 int = 123

If the type is clear from the initial value, you can omit the type.

var a2 = 123

When specifying an initial value, use := to omit var as well.

a3 := 123

You can group variable declarations as follows.

var (
    a1 int = 123
    a2 int = 456
)

The = operator assigns the value on the right to the variable on the left.

a1 = 456

You can also assign multiple values at the same time.

name, age = "devkuma", 23

Constants (const)

Use const to define a constant. For integers, the type can be omitted and is often not specified.

const foo = 100

You can group constant declarations as follows.

const (
    foo = 100
    baa = 200
)