[Go] Go Language Tutorial--Language Variables (5)

Past tutorials:

Variables come from mathematics and are abstract concepts in computer languages ​​that can store calculation results or represent values.

Variables can be accessed by variable name.

Go language variable names are composed of letters, numbers, and underscores, and the first character cannot be a number.

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

var identifier type

Multiple variables can be declared 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 one specifies the variable type, if not initialized, the variable defaults to a zero value.

var v_name v_type
v_name = value

The zero value is the value that the system defaults to when the variable is not initialized.

example

package main
import "fmt"
func main() {
    
    

    // 声明一个变量并初始化
    var a = "RUNOOB"
    fmt.Println(a)

    // 没有初始化就为零值
    var b int
    fmt.Println(b)

    // bool 零值为 false
    var c bool
    fmt.Println(c)
}

The execution result of the above example is:

RUNOOB
0
false
  • 0 for numeric types (including complex64/128)

  • Boolean type is false

  • String is "" (empty string)

  • The following types are nil:

var a *int
var a []int
var a map[string] int
var a chan int
var a func(string) int
var a error // error 是接口

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 is to determine the variable type by itself according to 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 type, if the variable has been declared with var, and then use := to declare the variable, a compilation error will occur. 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

multivariate declaration

//类型相同多个变量, 非全局变量
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 // 出现在 := 左侧的变量不应该是已经被声明过的,否则会导致编译错误


// 这种因式分解关键字的写法一般用于声明全局变量
var (
    vname1 v_type1
    vname2 v_type2
)

example

package main
import "fmt"

var x, y int
var (  // 这种因式分解关键字的写法一般用于声明全局变量
    a int
    b bool
)

var c, d int = 1, 2
var e, f = 123, "hello"

//这种不带声明格式的只能在函数体中出现
//g, h := 123, "hello"

func main(){
    
    
    g, h := 123, "hello"
    println(x, y, a, b, c, d, e, f, g, h)
}

The execution result of the above example is:

0 0 0 false 1 2 123 hello 123 hello

Value Types and Reference Types

All primitive types like int, float, bool, and string are value types, and variables using these types point directly to values ​​stored in memory:

insert image description here

When using the equal sign = to assign the value of one variable to another variable, such as: j = i, the value of i is actually copied in memory:

insert image description here

You can use &i to get the memory address of variable i, for example: 0xf840000040 (the address may be different each time).

The value of a value type variable is stored on the heap.

The memory address will vary depending on the machine, and even the same program will have different memory addresses after being executed on different machines. Because each machine may have a different memory layout, and the location allocation may also be different.

More complex data usually requires the use of multiple words, and these data are generally stored using reference types.

A variable r1 of reference type stores the memory address (number) where the value of r1 is located, or the location of the first word in the memory address.

insert image description here

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

Multiple words pointed to by a pointer of the same reference type can be in continuous memory addresses (the memory layout is continuous), which is also a form of storage with the highest computational efficiency; these words can also be scattered and stored in memory, each Each word indicates the memory address where the next word is located.

When using the assignment statement r2 = r1, only references (addresses) are copied.

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

Short form, use the := assignment operator

We know that the type of the variable can be omitted when the variable is initialized and automatically inferred by the system. It is actually a bit redundant to write the var keyword in the declaration statement, so we can abbreviate them as a := 50 or b := false.

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

This is the preferred form of using variables, but it can only be used in the body of the function, not for the declaration and assignment of global variables. Using the operator := efficiently creates a new variable, called an initialization declaration.

Note
If in the same code block, we cannot use the initialization declaration for the variable with the same name again, for example: a := 20 is not allowed, and the compiler will prompt an error no new variables on left side of :=, But a = 20 is ok because it is assigning a new value to the same variable.

If you use variable a before defining it, you will get compile 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, such as the 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 get the error a declared but not used.

In addition, it is not enough to simply assign a value to a, this value must be used, so use

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

will remove the error.

But global variables are allowed to be declared but not used. Multiple variables of the same type can be declared on the same line, such as:

var a, b, c int

Multiple variables can be assigned on the same line, such as:

var a, b int
var c string
a, b, c = 5, 7, "abc"

The above line assumes that the variables a, b and c have been declared, otherwise they should be used 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 a has the value 5, b has the value 7, and c has the value "abc".

This is known as 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, eg the value 5 is discarded in: _, b = 5, 7.

_ is actually a write-only variable, you cannot get its value. This is done because in Go you have to use all declared variables, but sometimes you don't need to use all return values ​​from a function.

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

Guess you like

Origin blog.csdn.net/u011397981/article/details/131543946