当类型为 interface{} 时初始化 nil 指针

Initialize nil pointer when the type is interface{}

我想知道当 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

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

使用此代码:

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.