79386332

Date: 2025-01-25 07:28:45
Score: 0.5
Natty:
Report link

Use answers in Sizeof struct in Go, but start with a nil pointer to the type:

type Coord3d struct {
    X, Y, Z int64
}

// Option 1:

ptrType := reflect.TypeFor[*Coord3d]()
valueType := ptrType.Elem()
size := valueType.Size()
fmt.Println(size)  // prints 24

// Option 2:

size = unsafe.Sizeof(*(*Coord3d)(nil))
fmt.Println(size) // prints 24

https://play.golang.com/p/Bj8hvQ3aPeP

The simplest approach is to rely on compiler optimizations.

size = unsafe.Sizeof(Coord3d{})
fmt.Println(size) // prints 24

Because the value of Coord3d{} is not used, the compiler does not allocate it.

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Unregistered user (0.5):
  • Low reputation (1):
Posted by: Reflected Bias