所以我有一些接口(interface)和结构:
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”)?我将这些指针存储在组件 slice 中,因为有多种类型可以实现组件。我试过这样做:
func Swap(component *Component, value Component){
*component = value
}
但是这不起作用(它运行但新值未更新)。如何取消引用组件并为其赋值?
最佳答案
您应该使用 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 .
关于pointers - 如何修改结构指针类型的接口(interface)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62732499/