Help us shape the future of Go! Take the 2026 Go Developer Survey

Source file src/runtime/sizeof_test.go

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package runtime_test
     6  
     7  import (
     8  	"reflect"
     9  	"runtime"
    10  	"testing"
    11  	"unsafe"
    12  )
    13  
    14  // Assert that the size of important structures do not change unexpectedly.
    15  // When a size changes, also report whether the structure moves to a
    16  // different size class, because that changes how much memory each object
    17  // takes.
    18  
    19  func TestSizeof(t *testing.T) {
    20  	const _64bit = unsafe.Sizeof(uintptr(0)) == 8
    21  	const xreg = unsafe.Sizeof(runtime.XRegPerG{}) // Varies per architecture
    22  	var tests = []struct {
    23  		val    any     // type as a value
    24  		_32bit uintptr // size on 32bit platforms
    25  		_64bit uintptr // size on 64bit platforms
    26  	}{
    27  		{runtime.G{}, 284 + xreg, 448 + xreg}, // g, but exported for testing
    28  		{runtime.Sudog{}, 64, 104},            // sudog, but exported for testing
    29  	}
    30  
    31  	if xreg > runtime.PtrSize {
    32  		t.Errorf("unsafe.Sizeof(xRegPerG) = %d, want <= %d", xreg, runtime.PtrSize)
    33  	}
    34  
    35  	for _, tt := range tests {
    36  		want := tt._32bit
    37  		if _64bit {
    38  			want = tt._64bit
    39  		}
    40  		got := reflect.TypeOf(tt.val).Size()
    41  		if want != got {
    42  			t.Errorf("unsafe.Sizeof(%T) = %d, want %d", tt.val, got, want)
    43  			gotClass, wantClass := runtime.AllocSize(got), runtime.AllocSize(want)
    44  			if gotClass != wantClass {
    45  				t.Errorf("%T moves from the %d-byte to the %d-byte size class, %+d bytes per object", tt.val, wantClass, gotClass, int(gotClass)-int(wantClass))
    46  			}
    47  		}
    48  	}
    49  }
    50  

View as plain text