英文:
Stack variables in go?
问题
以下是代码的中文翻译:
package main
import (
"fmt"
"os"
)
func main() {
var l = test(4)
test(5)
fmt.Fprintf(os.Stdout, "%d\n", *l)
}
func test(v int) *int {
var p = v
return &p
}
在C语言中,等效的代码会打印出5,因为第一个栈帧中的变量p会被第二个栈帧中的相同变量p覆盖。我反汇编了这段代码,但对其意义并不能理解太多。
#include <stdio.h>
int* test(int v);
int main() {
int* p = test(4);
test(5);
printf("%d\n", *p);
}
int* test(int v) {
int p = v;
return &p;
}
有人能给我一个关于Go语言内存管理工作原理的基本概述吗?函数变量是否存放在堆上?
英文:
package main
import (
"fmt"
"os"
)
func main() {
var l = test(4)
test(5)
fmt.Fprintf(os.Stdout, "%d\n", *l)
}
func test(v int) *int {
var p = v
return &p
}
In C, the equivalent code would print 5 because the the variable p in the first stack frame would be overwritten by the same variable p in the second stack frame. I disassembled the code but am not able to make too much sense of it.
#include <stdio.h>
int* test(int v);
int main() {
int* p = test(4);
test(5);
printf("%d\n", *p);
}
int* test(int v) {
int p = v;
return &p;
}
Can somebody give me a basic synopsis of how memory management works in Go? Do function variables go on the heap?
答案1
得分: 1
这是一段关于逃逸分析的内容。逃逸分析在官方文档中并不完善,但你可以参考这个链接:http://blog.rocana.com/golang-escape-analysis
你可以使用以下命令对你的代码进行逃逸分析(假设你的文件名是main.go):
go run -gcflags '-m -l' main.go
英文:
It is somewhat strange that we don't have good official documentation on escape analysis (or maybe even if it's there I haven't found it yet!) but here's something I found useful : http://blog.rocana.com/golang-escape-analysis
You can use something like this to do an escape analysis for your code (assuming your filename is main.go):
go run -gcflags '-m -l' main.go
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论