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?
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
", reflect.TypeOf(i).Size())
fmt.Printf("Size of var (unsafe.Sizeof): %d
", 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.
The equivalent of sizeof
in go is unsafe.Sizeof
. One difference between it and sizeof in C is that it's only defined on values (whereas in C, it works for values and types). The other main difference is that in go it's hardly ever needed, whereas in C it's fairly common.
An example is:
package main
import (
"fmt"
"unsafe"
)
func main() {
fmt.Println(unsafe.Sizeof(int(0)))
}
If you simply want to find out the size of an int
or uint
, use strconv.IntSize
.
const IntSize = intSize
IntSize
is the size in bits of anint
oruint
value.
For example,
package main
import (
"fmt"
"runtime"
"strconv"
)
func main() {
fmt.Println(runtime.Compiler, runtime.GOARCH, runtime.GOOS)
fmt.Println(strconv.IntSize)
}
Output:
gc amd64 linux
64
Not really an answer but the continuation of the comments thread following the original question…
To implement an in-memory dataset, I would took one of these approaches:
(Simple-minded): just use arrays of interface{}
to store rows.
Each value of interface type is a tuple of two pointers: a pointer to the enclosed value's real type and the value itself. Implementation is gc
(and gccgo
, I beleive) is smart enough to store values directly in that pointer space if its size is ≤ the size of uintptr
type on the target platform.
(Supposedly more advanced): store type information for your columns in a separate data structure (an array or slice); the type information might be obtained with tools from the reflect
package. Then store actual data in rows which are arrays of unsafe.Pointer
and play the same trick the implementation of interfaces in gc
does with values using type conversions from/to unsafe.Pointer
.
This would allow you to be more space-efficient by not storing a type of a value along with each contained value. Not sure about real performance benefits, if any.