SoFunction
Updated on 2025-03-05

Variable declaration and assignment in Go language

1. Variable declaration and assignment syntax

Variable declarations in Go language use the keyword var, e.g.

Copy the codeThe code is as follows:

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.

Copy the codeThe code is as follows:

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.

Copy the codeThe code is as follows:

var name = "tom"

Go also provides a shorter way of writing

Copy the codeThe code is as follows:

name := "tom"

In Go, the same variable cannot be declared multiple times. For example, the following code is not allowed:

Copy the codeThe code is as follows:

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:

Copy the codeThe 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

Copy the codeThe code is as follows:

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