简体   繁体   中英

How to initialize an empty pointer by reflect

This is a very straight forward question.

How do you implement Initialize() below with reflect ? Or is this possible?

func Initialize(v interface{}) {
    // ... some reflection code
}

type MyType struct {
    Name string
}

func main() {
    var val *MyType

    // val is nil before initialize
    Initialize(val)
    // val is now &MyType{Name: ""}

    // ...
}

```

Here's how to do it:

func Initialize(v interface{}) {
  rv := reflect.ValueOf(v).Elem()
  rv.Set(reflect.New(rv.Type().Elem()))
}

This function must be called with a pointer to the value to set:

Initialize(&val)

playground example

The code in this answer panics if the argument type is not a pointer to a pointer. Depending on your use, you might want to check the reflect value kind before calling Elem().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM