Variable 1. Variable declaration
Using the keyword var
var v1 int //整型var v2 string //字符串var v3 [10]int //数组var v4 []int //数组切片var v5 struct { //结构体 f int}var v6 *int //指针var v7 map[string] //map,key为string类型,value为int类型
Another use is to put a number of variables that need to be declared together
var ( v1 int v2 string)
2. Variable initialization
There are three ways of initializing variables:
var v1 int = 10 //方式1var v2 = 10 //方式2,编译器可以自动推导出v2的类型v3 := 10 //方式3,可以省略关键字var和类型,编译器可以自动推导出v3的类型
Note: the variable on the left is not already declared, otherwise it will cause a compilation error
4. Assigning values to variables
In the go language, variable initialization and variable assignment are two different concepts
var v10 int v10 = 123
Note: The go language supports multiple assignments, which is also supported in Python.
i, j = j, i //交换i和j变量
5. Anonymous variables
_ (underscore) is a special variable name, and any value given to it will be discarded:
_, i, _, j := 1, 2, 3, 4func test() (int, string) { return 250, "sb"}_, str := test()
Go language Primer to discard-variable