go是如何分配内存的?

func main() {
    a := 1
    b := 2
    c := "hello world"
    d := 1
    fmt.Printf("var a address is %p\n", &a)//var a address is 0xc0420361d0
    fmt.Printf("var b address is %p\n", &b)//var b address is 0xc0420361d8
    fmt.Printf("var c address is %p\n", &c)//var c address is 0xc0420361e0
    fmt.Printf("var d address is %p\n", &d)//var d address is 0xc0420361f0

}

变量c的大小明显超过了2B,为什么还是只占了2B的长度?golang的变量内存是如何分配的?

已邀请:

astaxie - 创造、获取、分享、传播和应用Go

赞同来自: tonyluj

string 类型在Go内部是一个struct类型,https://github.com/golang/go/blob/master/src/runtime/string.go#L213-L216

astaxie - 创造、获取、分享、传播和应用Go

赞同来自:

我刚在play.golang.org上面测试了以下,看上去有些是stack,有些在heap

package main

import (
    "fmt"
)

type A struct {
    B string
}

func main() {
    a := 1
    b := 2
    c := "hello world"
    d := 1
    e := A{}
    f := 1
    fmt.Printf("var a address is %p\n", &a)
    fmt.Printf("var b address is %p\n", &b)
    fmt.Printf("var c address is %p\n", &c)
    fmt.Printf("var d address is %p\n", &d)
    fmt.Printf("var e address is %p\n", &e)
    fmt.Printf("var f address is %p\n", &f)
}

输出

var a address is 0x1040e0f8
var b address is 0x1040e0fc
var c address is 0x1040a120
var d address is 0x1040e130
var e address is 0x1040a128
var f address is 0x1040e134

godonggua - java,go爱好者

赞同来自:

应该是16个字节吧, 我试了下 不管我的字符串多大,string的地址都是16字节, 当然这都是栈里的空间,估计这16字节里应该有8个字节存放了heap的地址。 我电脑是64位,不知道32位机器是多少,我觉得32位机器里 string应该是8个字节,因为指针值占 4个字节。
纯属本菜狗猜想,因为是内建类型,不知道string在go里是怎么处理的。

wayslog - 你们不喜欢我一定是你们的错

赞同来自:

堆还是栈是根据逃逸分析来的吧,像一些const的string根本没必要仍在堆上啊,栈上更快。

要回复问题请先登录注册