怎么new一个指针_19. Go语言里的 make 和 new 有什么区别?
大家好,我是明哥。
由于某些不可抗力,之前該專欄的所有內(nèi)容都被刪除了。因此之后的一段時(shí)間內(nèi),我會(huì)重新發(fā)布這些文章,先給已經(jīng)看過(guò)的關(guān)注者提個(gè)醒。
本文原文:http://golang.iswbm.com
Github:http://github.com/iswbm/GolangCodingTime
1. new 函數(shù)
在官方文檔中,new 函數(shù)的描述如下
// 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. func new(Type) *Type可以看到,new 只能傳遞一個(gè)參數(shù),該參數(shù)為一個(gè)任意類型,可以是Go語(yǔ)言內(nèi)建的類型,也可以是你自定義的類型
那么 new 函數(shù)到底做了哪些事呢:
- 分配內(nèi)存
- 設(shè)置零值
- 返回指針(重要)
舉個(gè)例子
import "fmt"type Student struct {name stringage int }func main() {// new 一個(gè)內(nèi)建類型num := new(int)fmt.Println(*num) //打印零值:0// new 一個(gè)自定義類型s := new(Student)s.name = "wangbm" }2. make 函數(shù)
在官方文檔中,make 函數(shù)的描述如下
//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.
func make(t Type, size ...IntegerType) Type
翻譯一下注釋內(nèi)容
注意,因?yàn)檫@三種類型是引用類型,所以必須得初始化(size和cap),但是不是置為零值,這個(gè)和new是不一樣的。
舉幾個(gè)例子
//切片 a := make([]int, 2, 10) // 字典 b := make(map[string]int)// 通道 c := make(chan int, 10)3. 總結(jié)
new:為所有的類型分配內(nèi)存,并初始化為零值,返回指針。
make:只能為 slice,map,chan 分配內(nèi)存,并初始化,返回的是類型。
另外,目前來(lái)看 new 函數(shù)并不常用,大家更喜歡使用短語(yǔ)句聲明的方式。
a := new(int) *a = 1 // 等價(jià)于 a := 1但是 make 就不一樣了,它的地位無(wú)可替代,在使用slice、map以及channel的時(shí)候,還是要使用make進(jìn)行初始化,然后才可以對(duì)他們進(jìn)行操作。
好了,今天的文章就到這里了。
若今天的分享對(duì)你有幫助,不如點(diǎn)個(gè)贊,支持一下?
總結(jié)
以上是生活随笔為你收集整理的怎么new一个指针_19. Go语言里的 make 和 new 有什么区别?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 迅雷第三季度净利润 440 万美元同比降
- 下一篇: 真香机?曝iPhone 16系列全系上高