dtiopy6088 2015-10-15 14:52
浏览 20
已采纳

我可以使用&运算符在函数中获取有效的指针,即使该函数已在golang中返回

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条回答 默认 最新

  • doumengbai2031 2015-10-15 14:56
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?