go 关键字指针 new和make

344 阅读2分钟

一 指针 Go里面的指针的作用一个是取地址(&) 一个是取值(*)

简单的几个case便于理解:

var a = 10
var b = &a
fmt.Printf("type:%T , b: %v", b, b) //type:*int , b:0xc00012a4f8

&a 是把a的内存地址赋值给b,所有b的类型是指针,存储的是a的内存地址

var a = 10
var b = &a
fmt.Printf("type:%T , b: %v", *b, *b) //type:int , b: 10

当使用*b的时候取到的是a的实际数值。*b 能把指针对应地址的值取出来即可。

当指针进行传值的时候,指针是可以把值取出来做修改的

func fn16(){
   var a = 1
   modify(a)
   fmt.Printf("a=%v \n", a)  // a = 1
   modify2(&a)    // 注意:这里传入的不是 a ,而是 a 的地址(指针)
   fmt.Printf("a=%v \n", a) // a=100
}

func modify(x int){
   x =10
   fmt.Println("type:%T,x: %v",x,x)
}

func modify2(x *int){
   *x = 100
}

二 new make 区别

go对于引用类型 的变量,使用时不仅要声明它,还要为其分配内存空间,否则无法存值。 对于值类型的变量,声明时不需要分配内存空间,因为在声明时已经默认分配好了内存。

func new(Type) *Type

// The new built-in function allocates memory. The first argument is a type,
// not a value, and the value returned is a pointer to a newly
// allocated zero value of that type.
  • 只接受一个参数,即:类型
  • 返回的是一个指针,即*Type,并且该指针对应的值为该类型的 零值
var a = new(int)  //返回指针,就是内存地址
fmt.Println(a)
fmt.Println(*a)

*a = 20;
fmt.Println(*a)

b := &a  //a的内存地址赋值给b
fmt.Printf("%T \n", b)  // **int
fmt.Println(b)  // 0xc000006028

make

func make(t Type, size ...IntegerType) Type

 The make built-in function allocates and initializes an object of type
// slice, map, or chan (only). Like new, the first argument is a type, not a
// value. Unlike new, make's return type is the same as the type of its
// argument, not a pointer to it. The specification of the result depends on
// the type:
// Slice: The size specifies the length. The capacity of the slice is
// equal to its length. A second integer argument may be provided to
// specify a different capacity; it must be no smaller than the
// length. For example, make([]int, 0, 10) allocates an underlying array
// of size 10 and returns a slice of length 0 and capacity 10 that is
// backed by this underlying array.
// Map: An empty map is allocated with enough space to hold the
// specified number of elements. The size may be omitted, in which case
// a small starting size is allocated.
// Channel: The channel's buffer is initialized with the specified
// buffer capacity. If zero, or the size is omitted, the channel is
// unbuffered.
```
```

make也是用于内存分配的,区别于new,
**它只用于slice、map以及channel的内存创建,而且它返回的类型就是这三个类型本身,而不是他们的指针类型**,因为这三种类型就是引用类型,所以就没有必要返回他们的指针了