Equivalent of sizeof(aType) in Go

c++, go, size, sizeof, types

Solution

If you want to find out the size of a particular value, there are two ways to do that - using the unsafe package, or using the reflection package. The following code demonstrates both:

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

func main() {
    var i int
    fmt.Printf("Size of var (reflect.TypeOf.Size): %d\n", reflect.TypeOf(i).Size())
    fmt.Printf("Size of var (unsafe.Sizeof): %d\n", unsafe.Sizeof(i))
}

However, I am not aware of a way to get the size of a type directly. But I think you'll find out that the sizeof function is not needed as often as in C.

Problem

C++ and several other languages have a function called `sizeof(int)` (or whatever type you need) that returns the number of bytes consumed by a particular data type, in the current system. Is there an equivalent function in Go? What is it?

Original source