reflection - Create new object knowing reflected type -


in function, 1 of arguments i'm passing

reflect.typeof(person) 

where person struct few strings. if function accepts argument, want instantiate empty struct knowing reflected type.

i have tried following

ins := reflect.new(typ)  //typ name or passed reflect.typeof(person) 

but returns me nil. doing wrong?

to tell you're doing wrong should see more of code. simple example how 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 value of reflect.value. returned value represents pointer new 0 value specified type.

you can use value.interface() extract pointer.

value.interface() returns value of type interface{}. can't return concrete type, general empty interface. empty interface not struct, can't refer field. may (and in case does) hold value of *person. can use type assertion obtain value of type *person.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -