Four ways to declare variables

Method one | declares variables and does not give initialization values

package main

import "fmt"

func main() {
        // Default is 0
	var num int

	fmt.Println("num =", num)
}
Copy the code

Num = 0 is displayed

Method two | declare a variable and initialize a value

package main

import "fmt"

func main() {
	var num int = 1000

	fmt.Println("num =", num)
}
Copy the code

Num = 1000 is displayed

Mode 3 | Can omit the data type during initialization and automatically match the data type of the current variable by value

package main

import "fmt"

func main() {
	var num = 1000

	fmt.Printf("typeof b = %T\n", num)
}
Copy the code

Typeof b = int

Mode 4 | omit var keyword, direct automatic matching (common method)

package main

import "fmt"

func main() {
	num: =1

	fmt.Printf("typeof b = %T num = %v\n", num, num)
}
Copy the code

Typeof b = int num = 1

Note that global variable declaration does not support method 4

A way to declare multivariables

Var declares multiple variables of the same type

package main

import "fmt"

func main() {
	var a, b int = 1.2
	fmt.Println(a, b)
}
Copy the code

The output is 1, 2

Var declares multiple variables of different types

package main

import "fmt"

func main() {
	var a, b = 1."String"
	fmt.Println(a, b)
}
Copy the code

The output is 1, 2

Var declares variables in multiple lines

package main

import "fmt"

func main() {
	var (
		a int    = 1
		b string = "2"
	)
	fmt.Println(a, b)
}
Copy the code

The output is 1, 2


If you are learning go for the first time, please correct your mistakes.