Variable declarations and assignments in the Go language

  • 2020-05-27 05:51:47
  • OfStack

1. Variable declaration and assignment syntax

Variable declarations in the Go language use the keyword var, for example


var name string // Declare a 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, tom is the value. The program above has two steps, step 1 to declare a variable and step 2 to assign a value to a variable. You can also combine the two steps to 1.


var name string = "tom"

If a value is assigned at the same time as the declaration, the variable type can be omitted. The Go language can determine the type of a variable based on its initial value, so it can also be written this way


var name = "tom"

The Go language also provides a shorter way to write it


name := "tom"

You cannot declare the same variable multiple times in Go. For example, the following code is not allowed:


i := 1
i := 2 // This is not allowed

:= indicates 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, in which the first letter cannot be a number.

A variable cannot be declared with the same name as the reserved word. Here is the reserved word:


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, sample


b := false // The Boolean
i := 1 // The integer
f := 0.618 // floating-point
c := 'a' // character
s := "hello" // string
cp := 3+2i  // The plural
i := [3]int{1,2,3} // An array of


Related articles: