【问题标题】:Initialize nil pointer when the type is interface{}类型为 interface{} 时初始化 nil 指针
【发布时间】:2021-08-02 06:02:04
【问题描述】:

initialize 函数接收到这个参数为interface{} 时,我想知道如何初始化一个指向结构的nil 指针。

假设我将始终发送一个指针,并且函数的参数类型严格为interface{},我该如何使这段代码工作?

type Foo struct {
}

func main() {
    var foo *Foo
    fmt.Println("foo is nil: ", foo)
    initialize(foo)
    fmt.Println("foo should not be nil: ", foo) // foo should be Foo{}, but it is nil
}

func initialize(fooPointer interface{}) {
    reflect.ValueOf(&fooPointer).Elem().Set(reflect.ValueOf(&Foo{}))
    fmt.Println("fooPointer is not nil: ", fooPointer)
}

https://play.golang.org/p/Va0bqXJGhWZ

【问题讨论】:

    标签: go reflection


    【解决方案1】:

    要修改被调用函数中的变量,必须将变量的地址传递给被调用函数。

    使用此代码:

    func main() {
        var foo *Foo
        fmt.Println("foo is nil: ", foo)
        initialize(&foo)  // <-- Pass address of variable
        fmt.Println("foo should not be nil: ", foo) // foo should be Foo{}, but it is nil
    }
    
    func initialize(fooPP interface{}) {
        // No need for & here because fooPP is a **Foo.
        reflect.ValueOf(fooPP).Elem().Set(reflect.ValueOf(&Foo{}))
        fmt.Println("fooPointer is not nil: ", fooPointer)
    }
    

    Run it on the playground.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      • 1970-01-01
      • 1970-01-01
      • 2019-10-28
      • 1970-01-01
      相关资源
      最近更新 更多