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"}
?
UPDATE: Unfortunately in real problem that I'm trying to solve I can not address original variable (panic: reflect: reflect.Value.Set using unaddressable value
), that's why I'm trying to workaround at pointer level.
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
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…