Go语言学习之new与make(The way to go)

来源:互联网 发布:阿里巴巴php招聘要求 编辑:程序博客网 时间:2024/06/05 13:24

生命不止,继续 go go go !!!

博客《Go语言学习之指针(The way to go)》中介绍了golang中的指针,我们用到了new:

package mainimport "fmt"func updateValue(someVal *int, someVal2 *float64) {    *someVal = *someVal + 100    *someVal2 = *someVal2 + 1.75    }func main() {    val := 1000    val2 := new(float64)    updateValue(&val, val2)    fmt.Println("val:", val)    fmt.Println("val2:", *val2)    }

可以看到new返回的是指针。

博客《Go语言学习之Arrays和Slices (The way to go)》中介绍了slice,用到了make:

x := make([]float64, 5, 10)

我想大多数人对new和make挺懵懂的,尤其是从c或c++过来的程序员。那么今天就详细介绍一下new与make的区别。

new
前面提到了,new表达式返回的指针:

p := new(chan int)   // p 的类型为 *chan int

用法:

new(Point)&Point{}     &Point{2, 3}  new(int)&int          // 错误

下面两种形式效果一样:

func newInt1() *int { return new(int) }func newInt2() *int {    var i int    return &i}

make
用途:
Create a channel
Create a map with space preallocated
Create a slice with space preallocated or with len != cap

返回:

c := make(chan int)  // c has type: chan int

区别
make用于内建类型(map、slice 和channel)的内存分配。new用于各种类型的内存分配。

内建函数new本质上说跟其它语言中的同名函数功能一样:new(T)分配了零值填充的T类型的内存空间,并且返回其地址,即一个*T类型的值。用Go的术语说,它返回了一个指针,指向新分配的类型T的零值。有一点非常重要:new返回指针。

内建函数make(T, args)与new(T)有着不同的功能,make只能创建slice、map和channel,并且返回一个有初始值(非零)的T类型,而不是*T。

These examples illustrate the difference between new and make.

var p *[]int = new([]int)       // allocates slice structure; *p == nil; rarely usefulvar v  []int = make([]int, 100) // the slice v now refers to a new array of 100 ints// Unnecessarily complex:var p *[]int = new([]int)*p = make([]int, 100, 100)// Idiomatic:v := make([]int, 100)

Remember that make applies only to maps, slices and channels and does not return a pointer. To obtain an explicit pointer allocate with new or take the address of a variable explicitly.

这里写图片描述

原创粉丝点击