Golang byte array size

I have a [] byte object, and I want to get its size in bytes. Is there an equivalent to C sizeof () in golang? If not, can you suggest other ways to get the same?

+8
sizeof go bytearray
source share
2 answers

To return the number of bytes in a byte fragment, use the len function:

 bs := make([]byte, 1000) sz := len(bs) // sz == 1000 

If you mean the number of bytes in the base array, use cap instead:

 bs := make([]byte, 1000, 2000) sz := cap(bs) // sz == 2000 

A byte is guaranteed to be one byte: https://golang.org/ref/spec#Size_and_alignment_guarantees .

+7
source share

I think your best bet would be:

 package main import "fmt" import "encoding/binary" func main() { thousandBytes := make([]byte, 1000) tenBytes := make([]byte, 10) fmt.Println(binary.Size(tenBytes)) fmt.Println(binary.Size(thousandBytes)) } 

https://play.golang.org/p/HhJif66VwY

Although there are many options, for example, simply import unsafe and use sizeof;

 import unsafe "unsafe" size := unsafe.Sizeof(bytes) 

Note that for some types, such as slices, Sizeof will give you the size of the slice descriptor, which is most likely not the one you want. Also, remember that the length and capacity of the slice are different, and the value returned by the binary .Size reflects the length.

+6
source share

All Articles