1. Variable declaration and assignment syntax
Variable declarations in Go language use the keyword var, e.g.
var name string //Declare variables
name = "tom" // Assign a value to the variable
This var is the keyword that defines the variable, name is the variable name, string is the variable type, = is the assignment symbol, and tom is the value. The above program is divided into two steps. The first step is to declare the variable and the second step is to assign values to the variable. You can also combine the two steps together.
var name string = "tom"
If the value is assigned at the same time during declaration, the variable type can be omitted. Go language can judge the type of variable based on the initial value, so it can also be written in this way.
var name = "tom"
Go also provides a shorter way of writing
name := "tom"
In Go, the same variable cannot be declared multiple times. For example, the following code is not allowed:
i := 1
i := 2 //This is not allowed
:= means declaration and assignment, so it is not allowed. After running, the system will prompt: no new variables on left side of :=
2. Variable naming rules
Variable names are composed of letters, numbers, and underscores, where the first letter cannot be a number.
The declaration of a variable cannot be the same as the reserved word, the following are reserved words:
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var
3. Example
b := false //Boolean
i := 1 //Integer
f := 0.618 //Floating point type
c := 'a' //character
s := "hello" //String
cp := 3+2i //plural
i := [3]int{1,2,3} //Array