pointers - 如何修改结构指针类型的接口(interface)值

标签 pointers go struct interface dereference

所以我有一些接口(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/

相关文章:

c# - 当两者相同,未知,类型时,您可以将一个结构复制到另一个吗

c - 字符串指针和字符串数组的区别

sql - Golang sql 包查询比 PostgreSQL SQL 查询慢

linux - 解决断开的符号链接(symbolic link)

json - Golang - 从 JSON 响应中隐藏空结构

c++ - 如何从 void 指针访问结构中的属性?

c - 如何在C中打印内存地址

c - 使用带指针的递归函数

c++ - 指针和 std::string - 奇怪的行为 - C++

javascript - 如何正确拒绝websocket升级请求?