【问题标题】:How to modify interface value of type struct pointer如何修改结构指针类型的接口值
【发布时间】:2020-10-25 04:29:13
【问题描述】:

所以我有一些接口和结构:

type Component interface{}

type Position struct{
    x float64
}

func Main(){
    var components []Components
    components = append(components, &Position{1.0})
    
    pos := components[0] // this is a Component, however reflect.TypeOf() returns *Position

    *pos = Position{2.0} // this won't compile as golang says you can't dereference a 'Component'
}

如何修改我检索到的 pos 变量中的实际值(例如更改“x”)?我将这些指针存储在组件切片中,因为有多种类型可以实现组件。 我试过这样做:

func Swap(component *Component, value Component){
    *component = value
}

但是这不起作用(它会运行但新值未更新)。如何取消引用组件并为其赋值?

【问题讨论】:

    标签: pointers go struct interface dereference


    【解决方案1】:

    你应该使用type assertions:

    package main
    
    import (
        "fmt"
    )
    
    type Component interface{}
    
    type Position struct {
        x float64
    }
    
    func (p Position) String() string {
        return fmt.Sprintf("%f", p.x)
    }
    
    func main() {
        components := []Component{&Position{1.0}}
        fmt.Println(components)
        
        pos, ok := components[0].(*Position)
        if !ok {
            panic("Not a *Position")
        }
        pos.x = 1000.0
        fmt.Println(components)
    }
    

    打印出来:

    [1.000000]
    [1000.000000]
    

    如果您需要检查多种类型,可以使用type switch

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2019-05-04
      • 2021-10-01
      • 1970-01-01
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多