なぜ調べたか
できるだけメモリを取らない型って何かな〜と思って調べてみました。
書いたコード
package main
import (
"fmt"
"unsafe"
)
var (
b bool
u8 uint8
u16 uint16
u32 uint32
u64 uint64
i8 int8
i16 int16
i32 int32
i64 int64
f32 float32
f64 float64
c64 complex64
c128 complex128
by byte
r rune
u uint
i int
up uintptr
str string
)
func main() {
fmt.Println("bool :", unsafe.Sizeof(b), "byte")
fmt.Println("uint8 :", unsafe.Sizeof(u8), "byte")
fmt.Println("uint16 :", unsafe.Sizeof(u16), "byte")
fmt.Println("uint32 :", unsafe.Sizeof(u32), "byte")
fmt.Println("uint64 :", unsafe.Sizeof(u64), "byte")
fmt.Println("int8 :", unsafe.Sizeof(i8), "byte")
fmt.Println("int16 :", unsafe.Sizeof(i16), "byte")
fmt.Println("int32 :", unsafe.Sizeof(i32), "byte")
fmt.Println("int64 :", unsafe.Sizeof(i64), "byte")
fmt.Println("float32 :", unsafe.Sizeof(f32), "byte")
fmt.Println("float64 :", unsafe.Sizeof(f64), "byte")
fmt.Println("complex64 :", unsafe.Sizeof(c64), "byte")
fmt.Println("complex128 :", unsafe.Sizeof(c128), "byte")
fmt.Println("byte :", unsafe.Sizeof(by), "byte")
fmt.Println("rune :", unsafe.Sizeof(r), "byte")
fmt.Println("uint :", unsafe.Sizeof(u), "byte")
fmt.Println("int :", unsafe.Sizeof(i), "byte")
fmt.Println("uintptr :", unsafe.Sizeof(up), "byte")
fmt.Println("string :", unsafe.Sizeof(str), "byte")
p := &struct {}{}
fmt.Println("struct pointer :", unsafe.Sizeof(p), "byte")
fmt.Println("struct value :", unsafe.Sizeof(*p), "byte")
f := func() {}
fmt.Println("function pointer :", unsafe.Sizeof(&f), "byte")
fmt.Println("function value :", unsafe.Sizeof(f), "byte")
}
実行結果
bool : 1 byte
uint8 : 1 byte
uint16 : 2 byte
uint32 : 4 byte
uint64 : 8 byte
int8 : 1 byte
int16 : 2 byte
int32 : 4 byte
int64 : 8 byte
float32 : 4 byte
float64 : 8 byte
complex64 : 8 byte
complex128 : 16 byte
byte : 1 byte
rune : 4 byte
uint : 8 byte
int : 8 byte
uintptr : 8 byte
string : 16 byte
struct pointer : 8 byte
struct value : 0 byte
function pointer : 8 byte
function value : 8 byte
ちなみに
- ポインタ型はどれも 8 byte
- 配列は 型のメモリサイズ * 要素数 byte
- mapは 8 byte
- sliceは 24 byte
- structは要素のメモリサイズの合計
でした。