In the below code:
c := "fool"
d := []byte("fool")
fmt.Printf("c: %T, %d
", c, unsafe.Sizeof(c)) // 16 bytes
fmt.Printf("d: %T, %d
", d, unsafe.Sizeof(d)) // 24 bytes
To decide the datatype needed to receive JSON data from CloudFoundry, am testing above sample code to understand the memory allocation for []byte
vs string
type.
Expected size of string
type variable c
is 1 byte x 4 ascii encoded letter = 4 bytes, but the size shows 16 bytes.
For byte
type variable d
, GO embeds the string in the executable program as a string literal. It converts the string literal to a byte slice at runtime using the runtime.stringtoslicebyte
function. Something like... []byte{102, 111, 111, 108}
Expected size of byte
type variable d
is again 1 byte x 4 ascii values = 4 bytes but the size of variable d
shows 24 bytes as it's underlying array capacity.
Why the size of both variables is not 4 bytes?