This is a creation in Article, where the information may have evolved or changed.
The go language defines variables using the keyword VAR, such as: Var x int=4
can also be written x:=4;
In a function, a :=
concise assignment statement can be used as an alternative definition where the explicit type is var
.
( :=
structs cannot be used outside of a function, and each syntax block outside of a function must start with a keyword.) )
package mainimport ( "fmt")func main() { var x int = 4 fmt.Println(x)//输出4 fmt.Println(&x)//输出指针 //fmt.Println(*x) //错误 y := 4 fmt.Println(y)//输出4 fmt.Println(&y)//输出指针 //fmt.Println(*y) //错误 var v *int = new(int)//返回值为指针 fmt.Println(*v)//输出为0,它只是将内存清零,而不是初始化内存*v = 4//赋值 fmt.Println(v)//输出指针 fmt.Println(*v)//输出4 z := new(int)//代替var v *int = new(int) *z = 3 fmt.Println(z)//输出指针 fmt.Println(*z)//输出3}
Summarize the variable definition of Go language the pointer is implied in the return value, so you can take the pointer operation and not tender the value operation.
the difference between new and make (GO)
Memory allocation
New is a built-in function that allocates memory, but unlike the work of new in other languages with the same name, it simply zeroed out the memory instead of initializing the memory. New (t) assigns a zero-value storage space and returns the address, which is a value of type *t, to a project of type T. In the terms of Go, it returns a pointer to the newly assigned 0 value of type T .
make(T,
args )
The purpose of the function is new(T)
different. It is used only to create slices, maps, and Chan (message Pipelines) and returns T
*T
an initialized (not 0 ) instance of the type (not). This difference arises because these three types are essentially references to data structures that must be initialized before they are used. For example, a slice is a descriptor with three items of content, including pointers, lengths, and capacities that point to data (inside an array), and the slice value is before the three items are initialized nil
. For slices, mappings, and channels, the make
internal data structures are initialized and the values that will be used are prepared. Such as:
The following code assigns an integer array with a length of 10, a capacity of 100, and a slice that returns the first 10 arrays
make([]int, 10, 100)
The following example illustrates new
the make
difference.
var p *[]int = new ([]int)//Allocate memory for the tile structure; *p = nil; var v []int = make ([]int, 10)//Slice V is now a new array of 10 integers Use//unnecessarily complicate the problem: var p *[]int = new ([]int) fmt. PRINTLN (p)//output: &[]*p = make ([]int, Ten, ten) fmt. PRINTLN (p)//output: &[0 0 0 0 0 0 0 0 0 0]fmt. Println ((*P) [2])//output: 0//Customary usage: V: = make ([]int) fmt. Println (v)//output: [0 0 0 0 0 0 0 0 0 0]