drm16022 2017-09-21 11:01
浏览 64
已采纳

在带有反射的接口下更改指针类型和值

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
}
  • 写回答

1条回答 默认 最新

  • douxihui8270 2017-09-21 11:09
    关注

    Everything in Go is passed by value. Interfaces too. When you pass a value of interface type, a copy of the interface value will be made (along with the (value;type) inside it), and you will only be able to modify the copy which will not affect the original.

    You have a variable a of interface type. If you want to modify the value stored in this variable, you have to pass / use the address of this variable.

    First let's modify the Greeter2.String() method to know which one gets called:

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

    And also call a.String() after first init to see that it originally does contain a *Greeter value as we'll soon change it.

    var a fmt.Stringer
    a = &Greeter{"John"}
    fmt.Println(a.String()) // Hello, My name is John
    
    v := reflect.ValueOf(&a).Elem()
    v.Set(reflect.ValueOf(&Greeter2{"Jack"}))
    fmt.Println(a.String()) // Hello2, My name is Jack
    
    a = &Greeter2{"Ron"}
    fmt.Println(a.String()) // Hello2, My name is Ron
    

    Output (try it on the Go Playground):

    Hello, My name is John
    Hello2, My name is Jack
    Hello2, My name is Ron
    

    So essentially there is no such thing as changing the value and type of an interface value, only changing the data in a variable (that has a memory address) that may be of interface type.

    So the key things were:

    1. Start from an address: reflect.ValueOf(&a)
    2. And you have to set a pointer value into it as only *Greeter2 implements fmt.String, but not Greeter. See Go, X does not implement Y (... method has a pointer receiver) for details.

    For more details and in-depth introducation, read: The Go Blog: The Laws of Reflection

    Edit: about modifying a copy

    First section of my answer: Whenever you pass something a copy is made. This also includes passing an interface value to reflect.ValueOf(): that will also receive a copy, so you can't avoid this. Only way to make this work is to pass a pointer; because the pointer will also be copied, but we're modifying the pointed value (not the pointer) which is the same.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败