go是如何分配内存的?
chenqinghe·2016-10-13 11:07:31·498次阅读·发布于 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的变量内存是如何分配的?

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

2022-01-21 12:48:16

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

2022-01-21 12:48:13

我刚在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
2022-01-21 12:48:04

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

2022-01-21 12:48:04
发起回帖
未登录,登录后可以回帖