Reputation: 2289
In function, one of arguments I'm passing
reflect.TypeOf(Person)
where person is struct
with few strings. If another function which accepts this argument, I want to instantiate this empty struct knowing its reflected type.
I have tried following
ins := reflect.New(typ) //typ is name or passed reflect.TypeOf(Person)
But this returns me nil
. What am I doing wrong?
Upvotes: 2
Views: 188
Reputation: 417462
To tell what you're doing wrong we should see more of your code. But this is a simple example how to do what you want:
type Person struct {
Name string
Age int
}
func main() {
p := Person{}
p2 := create(reflect.TypeOf(p))
p3 := p2.(*Person)
p3.Name = "Bob"
p3.Age = 20
fmt.Printf("%+v", p3)
}
func create(t reflect.Type) interface{} {
p := reflect.New(t)
fmt.Printf("%v\n", p)
pi := p.Interface()
fmt.Printf("%T\n", pi)
fmt.Printf("%+v\n", pi)
return pi
}
Output (Go Playground):
<*main.Person Value>
*main.Person
&{Name: Age:0}
&{Name:Bob Age:20}
reflect.New()
returns a value of reflect.Value
. The returned Value
represents a pointer to a new zero value for the specified type.
You can use Value.Interface()
to extract the pointer.
Value.Interface()
returns a value of type interface{}
. Obviously it can't return any concrete type, just the general empty interface. The empty interface is not a struct
, so you can't refer to any field. But it may (and in your case it does) hold a value of *Person
. You can use Type assertion to obtain a value of type *Person
.
Upvotes: 2