Can I use & operator to get a valid pointer in a function even if the function has returned in golang

huangapple go评论83阅读模式
英文:

Can I use & operator to get a valid pointer in a function even if the function has returned in golang

问题

一些代码如下所示:

type TUser struct {
    Name string
    Addr string
}

var UserMap map[int]*TUser // 将 TUser 指针保存到 map 中

func LoadUsers() {

    // ... ...
    // 假设 "row" 包含来自数据库表 "users" 的结果
    UserMap[0] = &TUser{Name: row["name"], Addr: row["addr"]}
}

我的问题是:
在函数 "LoadUsers" 返回后,"UserMap[0]" 中的指针是否有效?
还是会像在 C 语言中做相同的操作一样成为野指针?

谢谢。

英文:

some code as below

type TUser struct {
	Name	string
	Addr	string
}

var UserMap map[int]*TUser  //save TUser pointer to map

func LoadUsers() {

	... ...
	//assume "row" contains the results of table "users" from db
	UserMap[0] = &TUser{Name:row["name"], Addr:row["addr"]}
}

My question is:
After the function "LoadUsers" returns, is the pointer in "UserMap[0]" valid?
or it would become a wild pointer like we do the same thing in C language?

Thanks

答案1

得分: 6

是的,这是完全有效的。

根据常见问题解答

我如何知道变量是在堆上还是栈上分配的?

从正确性的角度来看,你不需要知道。在Go中,只要有对变量的引用,它就存在。实现选择的存储位置与语言的语义无关。

存储位置对编写高效程序有影响。在可能的情况下,Go编译器会将函数内部局部变量分配在该函数的堆栈帧中。然而,如果编译器无法证明变量在函数返回后不再被引用,那么编译器必须将变量分配在垃圾回收的堆上,以避免悬空指针错误。此外,如果一个局部变量非常大,将其存储在堆上而不是栈上可能更合理。

在当前的编译器中,如果一个变量的地址被取出,那么该变量有可能被分配在堆上。然而,基本的逃逸分析会识别一些情况,当这些变量在函数返回后不再存在时,它们可以驻留在栈上。

英文:

Yes, this is perfectly valid

From the FAQ:

> How do I know whether a variable is allocated on the heap or the stack?
>
> From a correctness standpoint, you don't need to know. Each variable
> in Go exists as long as there are references to it
. The storage
> location chosen by the implementation is irrelevant to the semantics
> of the language.
>
> The storage location does have an effect on writing efficient
> programs. When possible, the Go compilers will allocate variables that
> are local to a function in that function's stack frame. However, if
> the compiler cannot prove that the variable is not referenced after
> the function returns, then the compiler must allocate the variable on
> the garbage-collected heap to avoid dangling pointer errors. Also, if
> a local variable is very large, it might make more sense to store it
> on the heap rather than the stack.
>
> In the current compilers, if a variable has its address taken, that
> variable is a candidate for allocation on the heap. However, a basic
> escape analysis recognizes some cases when such variables will not
> live past the return from the function and can reside on the stack.

huangapple
  • 本文由 发表于 2015年10月15日 22:52:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/33151770.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定