Golang billion small details (var := new make)

@Golang Billion of small details (var := new make)
What you ignore is often the origin of the bug

var and:=

package main

import "fmt"

var a int

/*  var可以在任何地方定义变量,:=只能在函数内使用
a:=1
expected declaration
*/

func main() {
    
    
	var b int
	// var初始化,赋值零值,零值不一定是0哦!
	c := 1
	fmt.Println("c addr=",&c)
	/* 左侧没有新变量 报错了
	b,c := 2,5
	no new variables on left side of :=
	*/
	//左侧有新变量d,c重赋值
	d, c := 2, 5
	// 通过对比地址可以发现,只是赋值而已
	fmt.Println("d addr=",&d,"-","c addr=",&c)
	if true {
    
    
		// 此处可见,声明了同名变量b和c
		b,c := 2,5
		fmt.Println("b addr=",&b,"-","c addr=",&c)
		e, d := 7,8
		fmt.Println(b,"-",c,"-",e,"-",d)
		fmt.Println("d addr=",&d)
	}
	fmt.Println(a,"-",b,"-",c,"-",d)

	/*
	output:
	c addr= 0xc000012088
	d addr= 0xc0000120a8 - c addr= 0xc000012088
	b addr= 0xc0000120c0 - c addr= 0xc0000120c8
	2 - 5 - 7 - 8
	d addr= 0xc0000120d0
	0 - 0 - 5 - 2
	*/
}

varInitialization, assign zero value, zero value is not necessarily 0!
varVariables :=can be defined anywhere, and only when using
tip
:= for multi-value declaration and assignment in the function , if there is no newly declared variable on the left side, an error will be reported. If any, other variables that have already been declared are only Will be re-assigned, this rule should pay attention to the scope of the variable.

new() and make()

new()And make()are used to create objects.
make()The function is to initialize the built-in data structure, which is what we mentioned earlier slice,map ,chan;
new()the function is to allocate a piece of memory space according to the type passed in and return a pointer to this piece of memory space.
In fact, they All returned are reference types. A
reference type means that a variable directly stores an address value, and the space pointed to by this address value stores a value, such as a pointer.
There are also reference types in go. Please slice,map ,chan ,interfacenote that reference types cannot take their addresses.

import "fmt"

func main() {
    
    
	var a *int
	b :=1
	a = &b
	fmt.Println(a)
	/* 引用类型是无法取地址的
	fmt.Println(&a)
	*/
}

make()When an object is initialized, the corresponding runtime function is called according to the object type to initialize it. When it comes to this, have you thought of anything?

type T struct{
    
    

}

func newT() *T{
    
    
	return &T{
    
    }
}

make()newT()Does it look like ?

var and new

func main() {
    
    

	var t *T
	t =&T{
    
    }
	
	t1:= new(T)
	fmt.Println(reflect.TypeOf(t)==reflect.TypeOf(t1))
	// output:
	//  true
	//  可见两者等价
}

Guess you like

Origin blog.csdn.net/qq_17818281/article/details/114987050