type slice struct {
array unsafe.Pointer
len int cap int}
make操作
经常被问到new和make读区别,来看一看到底干来啥
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
funcmakeslice(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()
}
returnmallocgc(mem, et, true)
}
new操作
new是内置命令,源码位于open -a goland $GOROOT/src/builtin/builtin.go
go
1
2
3
4
// 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.funcnew(Type) *Type
funcslicecopy(to, fm slice, width uintptr) int {
if fm.len ==0|| to.len ==0 {
return0 }
n := fm.len
if to.len < n {
n = to.len
}
if width ==0 {
return n
}
if raceenabled {
callerpc :=getcallerpc()
pc :=funcPC(slicecopy)
racewriterangepc(to.array, uintptr(n*int(width)), callerpc, pc)
racereadrangepc(fm.array, uintptr(n*int(width)), callerpc, pc)
}
if msanenabled {
msanwrite(to.array, uintptr(n*int(width)))
msanread(fm.array, uintptr(n*int(width)))
}
size :=uintptr(n) * width
if size ==1 { // common case worth about 2x to do here// TODO: is this still worth it with new memmove impl?*(*byte)(to.array) = *(*byte)(fm.array) // known to be a byte pointer } else {
memmove(to.array, fm.array, size)
}
return n
}
评论