繁体   English   中英

如何修改结构指针类型的接口值

[英]How to modify interface value of type struct pointer

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

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
}

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

您应该使用类型断言

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]

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM