How come the sizeof string is giving is 16 Bytes where as int and float gives just 8 bytes as default. Also the address is for the any pointer (int, float, string) occupies 8bytes .
Can you any one please give detailed explanation. Thanks in advance…!!!
Posted below is sample code and output for your reference
Samle COde
package main
import (
“fmt”
“unsafe”
)
func main() {
a := “Hello\n”
fmt.Println(a, &a)
fmt.Printf(“address %T value %T Addresssize : %d and values size : %d”, &a, a, unsafe.Sizeof(&a), unsafe.Sizeof(a))
}
Output:
Hello
0xc000010230
address *string value string Addresssize : 8 and values size : 16
From the memory perspective, the string takes 16 bytes: 8 bytes for a pointer to the underlying array of bytes (you don’t have access to it ), 8 bytes for storing the length of array of the bytes
package main
import (
"fmt"
"unsafe"
)
func main() {
a := "Hello\n"
var aRuneCounter uint8
for range a {
aRuneCounter++
}
b := int8(2)
c := int32(332)
d := int64(23453)
e := "ąśóąśąłłęóąśa"
var eRuneCounter uint8
for range e {
eRuneCounter++
}
fmt.Println(a, &a)
fmt.Printf("address %T value %T Addresssize : %d and values size : %d len: %d rune counter: %d, %#v\n", &a, a, unsafe.Sizeof(&a), unsafe.Sizeof(a), len(a), aRuneCounter, []byte(a))
fmt.Printf("address %T value %T Addresssize : %d and values size : %d\n", &b, b, unsafe.Sizeof(&b), unsafe.Sizeof(b))
fmt.Printf("address %T value %T Addresssize : %d and values size : %d\n", &c, c, unsafe.Sizeof(&c), unsafe.Sizeof(c))
fmt.Printf("address %T value %T Addresssize : %d and values size : %d\n", &d, d, unsafe.Sizeof(&d), unsafe.Sizeof(d))
fmt.Printf("address %T value %T Addresssize : %d and values size : %d len: %d rune counter: %d, %#v\n", &e, e, unsafe.Sizeof(&e), unsafe.Sizeof(e), len(e), eRuneCounter, []byte(e))
}