Reputation: 121
which type's size is zero in slice of golang?
When I read the source code of golang slice, I found a code et.size == 0. so I want to know which type's size is 0?
func growslice(et *_type, old slice, cap int) slice {
...
if et.size == 0 {
if cap < old.cap {
panic(errorString("growslice: cap out of range"))
}
return slice{unsafe.Pointer(&zerobase), old.len, cap}
}
...
}
Upvotes: 1
Views: 838
Reputation: 166569
The Go Programming Language Specification
A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero. Two distinct zero-size variables may have the same address in memory.
For example,
package main
import (
"fmt"
"unsafe"
)
func main() {
type zero struct{}
fmt.Println(unsafe.Sizeof(zero{}))
slice := make([]zero, 7)
fmt.Printf("%d %v %p %p\n", len(slice), slice, &slice[0], &slice[len(slice)-1])
}
Playground: https://play.golang.org/p/pn8Rz0IorwD
Output:
0
7 [{} {} {} {} {} {} {}] 0x1c4c84 0x1c4c84
Upvotes: 2