其他分享
首页 > 其他分享> > golang new 和make 做了什么

golang new 和make 做了什么

作者:互联网

一般 使用的struct 的时候喜欢 new 一下 map chan make一下

new 是一个内置函数 go1.17/src/runtime/malloc.go:1233

func newobject(typ *_type) unsafe.Pointer {
	return mallocgc(typ.size, typ, true)
}

make 也是内置函数 go1.17/src/runtime/slice.go:83

func makeslice(et *_type, len, cap int) unsafe.Pointer {
	mem, overflow := math.MulUintptr(et.size, uintptr(cap))
	if overflow || mem > maxAlloc || len < 0 || len > cap {
		// NOTE: Produce a 'len out of range' error instead of a
		// 'cap out of range' error when someone does make([]T, bignumber).
		// 'cap out of range' is true too, but since the cap is only being
		// supplied implicitly, saying len is clearer.
		// See golang.org/issue/4085.
		mem, overflow := math.MulUintptr(et.size, uintptr(len))
		if overflow || mem > maxAlloc || len < 0 {
			panicmakeslicelen()
		}
		panicmakeslicecap()
	}

	return mallocgc(mem, et, true)
}

标签:mem,make,cap,len,golang,et,new,type
来源: https://www.cnblogs.com/guanchaoguo/p/16457656.html