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.

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c