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

我想知道如何初始化一个指向结构的nil指针,当函数接收此参数为.initializeinterface{}


假设我将始终发送一个指针,并且函数的参数类型严格,我如何使此代码工作?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


尚方宝剑之说
浏览 65回答 1
1回答

拉丁的传说

若要修改被调用函数中的变量,必须将变量的地址传递给被调用函数。使用以下代码:func main() {&nbsp; &nbsp; var foo *Foo&nbsp; &nbsp; fmt.Println("foo is nil: ", foo)&nbsp; &nbsp; initialize(&foo)&nbsp; // <-- Pass address of variable&nbsp; &nbsp; fmt.Println("foo should not be nil: ", foo) // foo should be Foo{}, but it is nil}func initialize(fooPP interface{}) {&nbsp; &nbsp; // No need for & here because fooPP is a **Foo.&nbsp; &nbsp; reflect.ValueOf(fooPP).Elem().Set(reflect.ValueOf(&Foo{}))&nbsp; &nbsp; fmt.Println("fooPointer is not nil: ", fooPointer)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go