Variable comes from mathematics and is an abstract concept in computer language that can store calculation results or represent values.

Go is statically typed, so variables are explicitly typed, and the compiler checks that they are typed correctly.

Variables can be accessed by variable names.

The Go language variable name consists of letters, digits, and underscores (_). The first character cannot be a digit.

1. Variable declaration

A common form of declaring a variable is to use the var keyword:

var name type
Copy the code

Var is the keyword for declaring variables, name is the name of variables, and type is the type of variables.

You can also declare multiple variables of the same type at once:

var name1,name2,name3 type
Copy the code

It is important to note that Go differs from many programming languages in declaring variables by putting their types after their names. The advantage of this is to avoid ambiguous declarations like those in C, such as: int* a, b; . Only a is a pointer and b is not. If you want both variables to be Pointers, you’ll need to write them separately. In Go, they can be declared as pointer types with ease:

var a, b *int
Copy the code

When a variable is declared, it is automatically given a zero value of that type: int 0, float 0.0, bool false, string empty string, pointer nil, and so on. All internals in Go are initialized.

The following is an example:

package main

import "fmt"

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

The following output is displayed:

0 0
Copy the code

Variable declarations take many forms, summarized below.

1.1 Standard declaration format

The standard format for variable declarations in Go is as follows:

varVariable name Variable typeCopy the code

or

varThe variable name1The variable name2Variable typesCopy the code

Variable declarations start with the keyword var, followed by the variable type, and do not need a semicolon at the end of the line.

If not initialized, the variable defaults to zero. (A zero value is the default value if the variable is not initialized.)

Declarations in the form of var are often used where the type of a variable needs to be explicitly specified, or where the initial value is irrelevant because the variable will be reassigned later.

The following is an example:

package main

import "fmt"

func main(a) {
	// Declare an uninitialized variable of type int with a default value of 0
	var a int
	fmt.Println(a)

	// Declare an uninitialized bool variable with a default value of zero false
	var b bool
	fmt.Println(b)
}
Copy the code

The following output is displayed:

0
false
Copy the code

1.2 Determine the variable type according to the value

varVariable name = variable valueCopy the code

The following is an example:

package main

import "fmt"

func main(a) {
	var c = true
	fmt.Println(c)
}
Copy the code

The following output is displayed:

true
Copy the code

1.3 Short variable declarations

In functions, an optional form called short variable declarations can be used to declare and initialize local variables. The format is as follows:

Variable name := variable valueCopy the code

The keyword var is omitted. The type of the variable name is determined by the type of the variable value, which can be the result value evaluated by any function or expression.

Because it is short and flexible, it is mainly used in the declaration and initialization of local variables.

Short variable declarations have the following caveats:

  • Define variables while explicitly initializing them.

  • Data types cannot be supplied directly.

  • It can only be used inside functions.

  • := denotes declaration, and = denotes assignment.

  • If the left side is a declared variable, it generates a compilation error. Such as:

    var intVal int
    intVal := 1		// A compilation error is generated
    Copy the code

The following is an example:

package main

import "fmt"

func main(a) {
	// Short variable declaration
	d := "xcbeyond"
	fmt.Println(d)
}
Copy the code

The following output is displayed:

xcbeyond
Copy the code

1.4 Batch Declaration

Think it’s cumbersome to declare variables with var on every line? Never mind, there’s another way to define variables for lazy people:

var (
	a int
    b string
    c float64
)
Copy the code

Using the keyword var and parentheses, you can put together a set of variable definitions.

The following is an example:

package main

import "fmt"

func main(a) {
    // Batch declaration
	var (
		e int
		f string
		g float64
	)
	fmt.Println(e,f,g)
}
Copy the code

The following output is displayed:

0  0
Copy the code

2. Initialization of variables

The standard format for variable initialization is as follows:

varVariable name type = variable valueCopy the code

Such as:

var i int = 100
Copy the code

I is the variable name of type int, and the initial value of I is 100.

In the above code, 100 and int are both types of int, and int can be considered redundant information, thus further simplifying initialization.

After omitting the type int from the standard format, the compiler attempts to deduce the type of the variable from its value to the right of the equal sign. Such as:

var i = 100
Copy the code

Short variable declarations and initializations, such as:

i := 100
Copy the code

This is the derivation declaration of the Go language. The compiler will automatically infer the corresponding type of an lvalue from an rvalue type.

3. Multiple assignments of variables

Assignment is used to update the value to which a variable refers. In its simplest form, it consists of the assignment =, the variable to the left of the symbol, and the expression to the right.

x = 1
person.name = "xcbeyond"
count[x] = count[x] * 5
Copy the code

Another form of assignment is multiple assignment, which allows several variables to be assigned at once.

In the Go language syntax, variable initialization and variable assignment are two different concepts. Go language variable assignment is the same as other languages, but Go language provides the multiple assignment function that other programmers have been waiting for, allowing variable exchange. Multiple assignment makes Go less code-intensive than other languages.

Take a simple algorithm to exchange variables as an example, the traditional writing is as follows:

var a int = 10
var b int = 20

var tmp int
tmp = a
a = b
b = t

fmt.Println(a, b)
Copy the code

The newly defined TMP variable requires memory, so someone designed a new algorithm to replace the intermediate variable, one of which is written as follows:

var a int = 10
var b int = 20

a = a ^ b
b = b ^ a
a = a ^ b

fmt.Println(a, b)
Copy the code

With multiple assignment, Go can be written as follows:

var a int = 10
var b int = 20

b, a = a, b

fmt.Println(a, b)
Copy the code

From the above examples, the Go language is much simpler. It should be noted that when multiple assignments are made, lvalues and rvalues are assigned from left to right. This method is used extensively in error handling and functions.

4. Anonymous variables

During coding, you may encounter variables, types, or methods that have no names. While not necessary, sometimes doing so can greatly increase the flexibility of your code, and these variables are collectively referred to as anonymous variables.

Anonymous variables are characterized by a underlined _, which itself is a special identifier, known as a blank identifier. It can be used to declare or assign to variables just like any other identifier (any type can be assigned to it), but any values assigned to this identifier are discarded, so they cannot be used in subsequent code, nor can this identifier be used as a variable to assign or operate on other variables. When using anonymous variables, you simply use the underlining substitution where the variable is declared.

For example, when programming in traditional strongly typed languages, we often have to define a bunch of useless variables in order to get a single value when we call a function because the function returns multiple values. In Go this situation can be avoided by using a combination of multiple returns and anonymous variables to make the code look more elegant.

The GetName() function returns firstName, lastName, and nickName.

package main

import "fmt"

func main(a) {
	// Anonymous variables
	firstName, _, _ := getName()
	_, lastName, _ := getName()
	_, _, nickName := getName()
	fmt.Println(firstName, lastName, nickName)
}

func getName(a) (firstName, lastName, nickName string) { 
    return "X"."C"."xcbeyond" 
} 
Copy the code

The following output is displayed:

X C xcbeyond
Copy the code

This makes the code very clear and basically blocks out anything that might confuse the reader of the code, greatly reducing communication complexity and code maintenance.

Anonymous variables take up no memory space and are not allocated. Anonymous variables are not unusable from one another because of multiple declarations.

5. Scope of variables

A variable (constant, type, or function) has a scope in a program, called scope.

Understanding the scope of variables is important for learning Go, because Go checks for unused variables at compile time and will report compilation errors if unused variables are present. If you don’t understand the scope of a variable, you can cause some unexplained compilation errors.

Depending on where a variable is defined, it can be divided into the following three types:

  • Local variables: variables defined within a function.
  • Global variables: variables defined outside a function.
  • Formal parameters: variables in a function definition.

Here are the introductions.

5.1 Local Variables

Variables declared in the body of a function are called local variables. They are scoped only in the body of a function. Parameters and return variables of a function are local variables.

A local variable does not always exist. It exists only after the function that defines it is called. The local variable is destroyed when the function call is complete.

Local variables a, b, and c are used in main() as shown in the following example:

package main

import "fmt"

func main(a) {
    // Declare local variables a and b and assign values
    var a int = 3
    var b int = 4
    
    // Declare the local variable c. and calculate the sum of a and b
    c := a + b
    fmt.Printf("a = %d, b = %d, c = %d\n", a, b, c)
}
Copy the code

The following output is displayed:

a = 3, b = 4, c = 7
Copy the code

5.2 Global Variables

Variables declared outside the function are called global variables. Global variables need only be defined in a source file and can be used in the source file. Of course, the source file that does not contain the global variable must use the keyword “import” to import the global variable into the source file.

Global variable declarations must be defined with the var keyword, and the first letter of a global variable must be capitalized if you want to use it in external packages.

Define the global variable c as shown in the following example:

package main

import "fmt"

// Declare global variables
var c int

func main(a) {
    // Declare local variables
    var a, b int
    
    // Initialize parameters
    a = 3
    b = 4
    c = a + b
    
    fmt.Printf("a = %d, b = %d, c = %d\n", a, b, c)
}
Copy the code

The following output is displayed:

a = 3, b = 4, c = 7
Copy the code

Global and local variables in Go programs can have the same name, but local variables in the function body are given priority.

5.3 Formal Parameters

When you define a function, the variables in parentheses after the function name are called formal parameters. Formal parameters take effect only when the function is called, and are destroyed after the function is called. When the function is not called, its parameters do not occupy the actual storage and have no actual value.

Formal parameters are used as local variables of the function.

The function sum(a, b int) defines formal parameters a and b as shown in the following example:

package main

import "fmt"

func main(a) {
	sum := sum(1.3)
	fmt.Println(sum)
}

// The sum of two numbers
func sum(a, b int) int{
	num := a + b
	return num
}
Copy the code

The following output is displayed:

4
Copy the code