使用初始化器了解变量

I am learning the basics of go (golang).

I can't seem to wrap my head around how variables with initializers work.

package main

import "fmt"

var i, j int = 100000, 5

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

When i print out j i get 5 instead of 100000, why is that?

When initializing multiple variables they are initialized in the order in which they are passed.

So if you are declaring first i then j, then the values 100000 then 5 are assigned in the same order.

When you print j you will get 5 because it is the second variable and corresponds to the second value.

This also applies to the same way that multiple variable returns work in go, example below, or working example here in the playground.

func doStuff() (string, int) {
    red, five := "red", 5
    return red, five
}

See this helpful resource for more information on working with variables, and this from the Tour of Go on working with multiple variable returns.

Clearly, i = 100000 and j = 5.

var i, j int = 100000, 5

is equivalent to

var i int = 100000
var j int = 5

Simply match the items in the variable list with the corresponding items in the initializer list.

The Go Programming Language Specification

Variable declarations

If a list of expressions is given, the variables are initialized with the expressions following the rules for assignments.

For example,

package main

import "fmt"

var i, j int = 100000, 5

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

Playground: https://play.golang.org/p/w821v9Tl1zx

Output:

100000 5