Alteração do tipo e valor do ponteiro na interface com reflexão
É possível alterar o tipo de ponteiro e o valor da variável definida pela interface?
Eu posso alterar o valor do ponteiro com reflexão:v.Elem().Set(reflect.ValueOf(&Greeter{"Jack"}).Elem())
que é equivalente aa = &Greeter{"Jack"}
.
Mas como posso fazer uma reflexão equivalente aa = &Greeter2{"Jack"}
?
ATUALIZAÇÃO: Infelizmente, no problema real que estou tentando resolver, não consigo resolver a variável original (panic: reflect: reflect.Value.Set using unaddressable value
), é por isso que estou tentando solucionar o problema no nível do ponteiro.
Aqui é um código de exemplo completo:
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
}