Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Go Language Variables

Go Language Variables

Variables originate from mathematics; they are an abstract concept in computer languages that can store computation results or represent values.

Variables can be accessed through their variable names.

Go variable names consist of letters, digits, and underscores, and the first character cannot be a digit.

The general form of declaring a variable is to use the var keyword:

var identifier type

You can declare multiple variables at once:

var identifier1, identifier2 type

Example

package

main

import

"fmt"

func

main

()

{

   

var

a

string

=

"Runoob"

    fmt

.

Println

(

a

)

   

var

b

,

c

int

=

1

,

2

    fmt

.

Println

(

b

,

c

)

}

The output of the above example is:

Runoob

1 2

Variable Declaration

The first approach: specify the variable type; if it is not initialized, the variable defaults to its zero value。



var v_name v_type

v_name = value

The zero value is the value set by default when a variable is not initialized.

Example

package

main

import

"fmt"

func

main

()

{

   

// declare a variable and initialize it

   

var

a

=

"RUNOOB"

    fmt

.

Println

(

a

)

   

// zero value if not initialized

   

var

b

int

    fmt

.

Println

(

b

)

   

// the zero value of bool is false

   

var

c

bool

    fmt

.

Println

(

c

)

}

The example above produces:



RUNOOB

0

false

var a []int var a map[string] int var a chan int var a func(string) int var a error // error is an interface

Example

package

main

import

"fmt"

func

main

()

{

   

var

i

int

   

var

f

float64

   

var

b

bool

   

var

s

string

    fmt

.

Printf

(

"%v %v %v %q\n"

,

i

,

f

,

b

,

s

)

}

The output is:

0 0 false ""

The second approach: determine the variable type automatically from the value.



var v_name = value

Example

package

main

import

"fmt"

func

main

()

{

   

var

d

=

true

    fmt

.

Println

(

d

)

}

The output is:

true

The third approach: if a variable has already been declared with var, declaring it again with := produces a compilation error. The format is:

v_name := value

For example:



var intVal int 

intVal :=1 // 这时候会产生编译错误,因为 intVal 已经声明,不需要重新声明

Just use the following statement directly:

intVal := 1 // 此时不会产生编译错误,因为有声明新的变量,因为 := 是一个声明语句

intVal := 1 is equivalent to:

var intVal int 

intVal =1 

var f string = "Runoob" can be shortened to f := "Runoob":

Example

package

main

import

"fmt"

func

main

()

{

    f

:=

"Runoob"

// var f string = "Runoob"

    fmt

.

Println

(

f

)

}

The output is:

Runoob

Multi-variable Declaration



//Multiple variables of the same type, non-global variables

var vname1, vname2, vname3 type

vname1, vname2, vname3 = v1, v2, v3



var vname1, vname2, vname3 = v1, v2, v3 // 和 python 很像,不需要显示声明类型,自动推断



vname1, vname2, vname3 := v1, v2, v3 // 出现在 := 左侧的变量不应该是已经被声明过的,否则会导致编译错误





// This kind of factorization keyword syntax is generally used to declare global variables

var (

    vname1 v_type1

    vname2 v_type2

)

Example

package

main

import

"fmt"

var

x

,

y

int

var

(

 

// this factored keyword form is generally used to declare global variables

    a

int

    b

bool

)

var

c

,

d

int

=

1

,

2

var

e

,

f

=

123

,

"hello"

// this form without a declaration clause can only appear inside a function body

//g, h := 123, "hello"

func

main

(){

    g

,

h

:=

123

,

"hello"

    fmt

.

Println

(

x

,

y

,

a

,

b

,

c

,

d

,

e

,

f

,

g

,

h

)

}

The example above produces:



0 0 0 false 1 2 123 hello 123 hello


Value Types and Reference Types

All basic types such as int, float, bool, and string are value types; variables of these types point directly to the value stored in memory:

When using the equals sign = to assign the value of one variable to another, such as:j = i, it actually copies the value of i in memory:

You can obtain the memory address of variable i with &i, for example: 0xf840000040 (the address may differ each time).

Value type variables are usually stored on the stack, especially when they are local variables. When the value of a value type variable needs to be used outside the function scope, Go allocates it on the heap.

Memory addresses vary from machine to machine, and even the same program running on different machines may produce different memory addresses. Each machine may have a different memory layout, and location allocation may also differ.

More complex data usually requires multiple words and is generally stored using reference types.

A reference-type variable r1 stores the memory address (a number) where the value of r1 is located, or the position of the first word at that memory address.

This memory address is called a pointer, and this pointer is itself actually stored in another value.

The multiple words pointed to by the pointer of the same reference type may be in contiguous memory addresses (the memory layout is contiguous), which is the most computationally efficient form of storage; alternatively, these words may be scattered in memory, with each word indicating the memory address of the next word.

When using the assignment statement r2 = r1, only the reference (address) is copied.

If the value of r1 is changed, all references to that value will point to the modified content; in this example, r2 will also be affected.


Short form, using the := assignment operator

We know that a variable's type can be omitted during initialization and inferred automatically by the system, so writing the var keyword in a declaration is somewhat redundant. Therefore, we can shorten them to a := 50 or b := false.

The types of a and b (int and bool) will be inferred automatically by the compiler.

This is the preferred form for using variables, but it can only be used inside a function body, not for the declaration and assignment of global variables. Using the := operator creates a new variable efficiently; this is known as a short variable declaration.

Notes

In the same code block, we cannot use a short variable declaration again for a variable with the same name. For example, a := 20 is not allowed, and the compiler reports the error "no new variables on left side of :=", but a = 20 is allowed because it assigns a new value to the same variable.

If you use variable a before defining it, you will get a compilation error: undefined: a.

If you declare a local variable but do not use it in the same code block, you will also get a compilation error, as with variable a in the following example:

Example

package

main

import

"fmt"

func

main

()

{

   

var

a

string

=

"abc"

   fmt

.

Println

(

"hello, world"

)

}

Trying to compile this code will produce the error a declared but not used。

In addition, simply assigning a value to a is not enough; the value must be used, so using

fmt.Println("hello, world", a)

will remove the error.

However, global variables are allowed to be declared but not used. Multiple variables of the same type can be declared on the same line, like this:



var a, b, c int

Multiple variables can be assigned on the same line, like this:



var a, b int

var c string

a, b, c = 5, 7, "abc"

The line above assumes that variables a, b, and c have all been declared; otherwise, you should write it like this:



a, b, c := 5, 7, "abc"

The values on the right are assigned to the variables on the left in the same order, so the value of a is 5, b is 7, and c is "abc".

This is called parallel or simultaneous assignment.

If you want to swap the values of two variables, you can simply use a, b = b, a; the two variables must be of the same type.

The blank identifier _ is also used to discard values, such as the value 5 in: _, b = 5, 7, which is discarded.

_ is actually a write-only variable; you cannot get its value. This is because in Go you must use all declared variables, but sometimes you do not need every value returned from a function.

Parallel assignment is also used when a function returns multiple values, for example here val and the error err are obtained simultaneously by calling the Func1 function: val, err = Func1(var1).