【问题标题】:What's the benefit of that escape in the reflect package在反射包中逃脱有什么好处
【发布时间】:2021-06-29 06:59:42
【问题描述】:
// reflect/value.go

func ValueOf(i interface{}) Value {
    if i == nil {
        return Value{}
    }

    // TODO: Maybe allow contents of a Value to live on the stack.
    // For now we make the contents always escape to the heap. It
    // makes life easier in a few places (see chanrecv/mapassign
    // comment below).
    escapes(i)

上面的代码是golang中Value.go的源码,escapes(i)上面的注释说明每次调用ValueOf函数,i都会逃到堆里,这是为什么呢?即,如何解释在一些地方让生活更轻松

【问题讨论】:

  • (see chanrecv/mapassign comment below) 他们说什么?
  • @tkausl // Note: some of the noescape annotations below are technically a lie, // but safe in the context of this package. Functions like chansend // and mapassign don't escape the referent, but may escape anything // the referent points to (they do shallow copies of the referent). // It is safe in this package because the referent may only point // to something a Value may point to, and that is always in the heap // (due to the escapes() call in ValueOf).
  • @tkausl 我不知道chanrecv/mapassign的评论的含义

标签: go reflection implementation


【解决方案1】:

我还在学习围棋,所以我无法描述更多,这就是社区 wiki 回答的原因。但这里是摘录的注释(在 chanrecv 函数上方的注释):

注意:下面的一些 noescape 注释在技术上是谎言, 但在这个包的上下文中是安全的。类似 chansend 的函数 和 mapassign 不会逃避所指对象,但可以逃避任何东西 所指对象指向(他们做所指对象的浅拷贝)。 它在这个包中是安全的,因为所指对象可能只指向 指向某个 Value 可能指向的东西,它总是在堆中 (由于 ValueOf 中的 escapes() 调用)。

另见:

// Dummy annotation marking that the value x escapes,
// for use in cases where the reflect code is so clever that
// the compiler cannot follow.
func escapes(x interface{}) {
    if dummy.b {
        dummy.x = x
    }
}

var dummy struct {
    b bool
    x interface{}
}

我希望这会有所帮助。

【讨论】:

  • 谢谢。 在这个包中是安全的,因为引用对象可能只指向一个 Value 可能指向的东西,并且总是在堆中。你这话有什么意义?这个词中的safe 是什么意思?气相色谱安全吗?参考安全吗?
  • @SimonHu 这不是我的话。这是在同一文件中的代码上找到的注释。我只是想帮忙。 :)
猜你喜欢
  • 2011-03-07
  • 1970-01-01
  • 2016-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 2011-04-04
相关资源
最近更新 更多