jeudi 21 septembre 2017

Changing pointer type and value under interface with reflection

Is it possible to change pointer type and value of variable defined by interface?

I can change pointer value with reflection: v.Elem().Set(reflect.ValueOf(&Greeter{"Jack"}).Elem()) which is equivalent to a = &Greeter{"Jack"}.

But how can I make a reflection equivalent for a = &Greeter2{"Jack"}?

Here is full example code:

package main

import (
    "fmt"
    "reflect"
)

type Greeter struct {
    Name string
}

func (g *Greeter) String() string {
    return "Hello, My name is " + g.Name
}

type Greeter2 struct {
    Name string
}

func (g *Greeter2) String() string {
    return "Hello, My name is " + g.Name
}

func main() {
    var a fmt.Stringer
    a = &Greeter{"John"}

    v := reflect.ValueOf(a)
    v.Elem().Set(reflect.ValueOf(&Greeter{"Jack"}).Elem())
    //v.Elem().Set(reflect.ValueOf(&Greeter2{"Jack"}).Elem()) // panic: reflect.Set: value of type main.Greeter2 is not assignable to type main.Greeter
    fmt.Println(a.String()) // Hello, My name is Jack

    a = &Greeter2{"Ron"}
    fmt.Println(a.String()) // Hello, My name is Ron
}





Aucun commentaire:

Enregistrer un commentaire