dreljie602951 2017-10-28 07:55
浏览 44
已采纳

在Go中处理悬空指针

I have been reading Rust and Go in parallel and I see subtle differences in how both these languages deal with dangling pointers and the problems it causes. For example, here is a version in Rust:

fn main() {
    let reference_to_nothing = dangle();
}

fn dangle() -> &String {
    let s = String::from("hello");

    &s
}

The above would error out saying that in the function dangle, s goes out of scope and I cannot return a reference to it! But in Go, this seems to be sort of allowed?

How is such a thing handled in Go? Is it easy to create dangling pointers in Go? If so what measures do I have to control them?

  • 写回答

1条回答 默认 最新

  • dqan70724 2017-10-28 08:16
    关注

    In Go, dangling pointers are not a thing, due to the way how escape analysis works. Suppose you have a code like this:

    func CreateUser(name string) *User {
        return &User{Name: name}
    }
    

    The compiler will understand that because the pointer can be accessed after the function exits, the structure should be allocated on heap. As Effective Go says:

    Note that, unlike in C, it's perfectly OK to return the address of a local variable; the storage associated with the variable survives after the function returns.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器