Go 内存布局

了解对象内存布局,有助于深入理解 Go 语言本身,写出更漂亮的代码

基本类型

类型 长度 默认值 说明
bool 1 false
byte 1 0 uint8
rune 4 0 Unicode point, int32
int/uint 48 0 32位/64位
int8/uint8 1 0 -128~127, 0~255
Int16/uint16 2 0 -32768~32767, 0~65535
Int32/uint32 4 0 -21亿~21亿, 0~42亿
Int64/uint64 8 0
float32 4 0.0
float64 8 0.0
complex64 8
complex128 16
uintptr 48 足以存储指针的 uint32/uint64 整数
array 值类型
struct 值类型
string ”" UTF-8 字符串
slice nil 引用类型
map nil 引用类型
chnnael nil 引用类型
interface nil 接口
function nil 函数

对象内存布局

在对基础类型的大小有基本概念后,可以来看下这些类型的内存布局

+--------+
|   1    |  int
+--------+
+--------+
|  3.14  |  float32
+--------+
+---+---+---+---+
| 1 | 2 | 3 | 4 | [4]int
+---+---+---+---+

string:

+---------+---------+ 
| pointer | len = 5 | s = "hello"
+---------+---------+
    |
    +---+---+---+---+---+
    | h | e | l | l | o | 
    +---+---+---+---+---+
        |
        +---------+---------+
        | pointer | len = 2 | [5]byte sub=s[1:3]
        +---------+---------+

struct:

+---+---+---+---+---+---+---+---+
| 1 | 2 | 0 | 0 | 3 | 0 | 0 | 0 | struct { a byte; b byte; c int32 } = { 1, 2, 3 } 
+---+---+---+---+---+---+---+---+
  a   b   c

+-----------+-----+
| pointer a |  b  |  struct{ a *int; b int }
+-----------+-----+
    |
    +-----+ 
    | int | 
    +-----+

slice:

+---------+---------+---------+
| pointer |  len=8  |  cap=8  | x=[]int{0,1,2,3,4,5,6,7} 
+---------+---------+---------+
    |
    +---+---+---+---+---+---+---+---+
    | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | [8]int 
    +---+---+---+---+---+---+---+---+
        |
        +---------+---------+---------+ 
        | pointer |  len=2  |  cap=5  | y=x[1:3:6] 
        +---------+---------+---------+

interface:

+---------+---------+
|  *itab  |  *data  | struct Iface
+---------+---------+
     |         |
     +------+  +------+ 
     | Itab |  | data | 
     +------+  +------+

new:

+---------+
| pointer |     s = new([3]int)
+---------+
    |
    +---+---+---+
    | 0 | 0 | 0 | [3]int
    +---+---+---+

make:

+---------+---------+---------+
| pointer |  len=1  |  cap=3  | slice=make([]int,1,3) 
+---------+---------+---------+
    |
    +---+---+---+ 
    | 0 | 0 | 0 | [3]int
    +---+---+---+

+---------+
| pointer | map = make(map[string]int); 实际返回的是⼀一个指针包装对象。
+---------+
    |
    ..................
    .                .
    . hashmap.c Hmap . 
    .                . 
    ..................

+---------+
| pointer | channel = make(chan int); 实际返回的是⼀一个指针包装对象。 
+---------+ 
    |
    ................ 
    .              . 
    . chan.c Hchan . 
    .              .
    ................