What is the

hello :="hello"

Short variable declaration is a way to declare variables in Golang. It is a special syntax of Golang. Compared with var hello=”hello” declaration, one less var can be written, which can slightly reduce the amount of code

The characteristics of

1. You can repeat the declaration

Strongly typed languages do not allow variables to be declared twice, and using var to declare variables repeatedly in Golang will also throw an error

package main
import "fmt"
func main() {
	var a = 100
	var a = 200
	fmt.Println(a)
}
Copy the code

A redeclared in this block is invalid

When using short variable declarations:

// example1: package main import "fmt" func main() { a, c := 100, 200 fmt.Println(&a) // 0xc000014090 a, d := 200, Println(a, c, d) Println(&a) // 0xC000014090}  no new variables on left side of := // example2: package main import "fmt" func main() { a, c := 100, 200 fmt.Println(&a) // 0xc000014090 a, d := 200, 300 ftt. Println(a, c, d) // 100,200,300 ftt. Println(&a) // 0xc000014090Copy the code

Variable A is declared twice in both example1 and example2, but only example2 will compile. You can see that repeated declarations are valid only if at least one of the variables to the left of the declaration is new.

Also note that the variable declared repeatedly isn’t created multiple times, with new values assigned to the original variable (it just assigns a new value to the original). The memory address of variable A in example2 is always the same

Also note that the declaration is repeated only in the same scope. If the same variable name is declared in different scopes, a new variable is created

Package main import "FMT" func main() {// scope 1 a, b := 100, 200 if true {// scope 2 a, c := 300, 400 FMT.Println(a, } FMT.Println(a, b) // 100,200Copy the code

The above variable A is in two different scopes, which are completely different variables

2. Can only be declared in local scope

It cannot be declared in a global scope, but only in a local scope, including inside functions, if,for, and switch statements

func main() {
	for i := 0; i < 100; i++ {
		fmt.Println(i)
	}

	if ok := true; ok {
			fmt.Println(ok)
		}
}
Copy the code

Reference:

[Short variable declarations](https://golang.org/ref/spec#Short_variable_declarations)