Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions compiler/sizes.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ func (s *stdSizes) Alignof(T types.Type) int64 {
// of alignment of the elements and fields, respectively.
switch t := T.Underlying().(type) {
case *types.Array:
if t.Len() == 0 {
// 0-sized arrays, always have 0 size.
// And from the spec, should have an alignment of _at least_ 1
return 1
}

// spec: "For a variable x of array type: unsafe.Alignof(x)
// is the same as unsafe.Alignof(x[0]), but at least 1."
return s.Alignof(t.Elem())
Expand Down
10 changes: 10 additions & 0 deletions testdata/reflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ func main() {
println("\nvalues of interfaces")
var zeroSlice []byte
var zeroFunc func()
// by embedding a 0-array func type in your struct, it is not comparable
type doNotCompare [0]func()
type notComparable struct {
doNotCompare
data *int32
}
var zeroMap map[string]int
var zeroChan chan int
n := 42
Expand Down Expand Up @@ -170,6 +176,10 @@ func main() {
assertSize(reflect.TypeOf(new(int)).Size() == unsafe.Sizeof(new(int)), "*int")
assertSize(reflect.TypeOf(zeroFunc).Size() == unsafe.Sizeof(zeroFunc), "func()")

// make sure embedding a zero-sized "not comparable" struct does not add size to a struct
assertSize(reflect.TypeOf(doNotCompare{}).Size() == unsafe.Sizeof(doNotCompare{}), "[0]func()")
assertSize(unsafe.Sizeof(notComparable{}) == unsafe.Sizeof((*int32)(nil)), "struct{[0]func(); *int32}")

// Test that offset is correctly calculated.
// This doesn't just test reflect but also (indirectly) that unsafe.Alignof
// works correctly.
Expand Down