methods for declaring and assigning variables in the Go language
This article mainly introduces the go language variable declaration and assignment methods, very detailed and comprehensive, the need for small partners can refer to.
1, variable declaration and assignment syntax
Variable declarations in the Go language use keyword var, for example
The code is as follows:
var name string//declaration variable
Name = "Tom"//Assign a value to a variable
Here 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 to assign a value to the variable. You can also combine the two steps together.
The code is as follows:
var name string = "Tom"
If you assign a value at the same time as the declaration, you can omit the variable type, and the go language can determine the type of the variable based on the initial value, so you can also write
The code is as follows:
var name = "Tom"
The Go language also provides a shorter way of writing
The code is as follows:
Name: = "Tom"
You cannot declare multiple times on the same variable in the Go language. For example, the code for the following example is not allowed:
The code is as follows:
I: = 1
I: = 2//This is not allowed
: = declaration and assignment, so it is not allowed, the system will prompt after the run: No new variables on the left side of: =
2. Variable naming rules
Variable names consist of letters, numbers, and underscores, where the first letter cannot be a number.
The declaration of a variable cannot have the same name as a reserved word, and the following are reserved words:
The code is as follows:
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
The code is as follows:
B: = False//Boolean
I: = 1//integral type
F: = 0.618//floating-point type
c: = ' a '/character
s: = "Hello"//String
CP: = 3+2i//plural
I: = [3]int{1,2,3}//Array