相关疑难解决方法(0)

按名称访问struct属性

这是一个不起作用的简单go程序:

package main
import "fmt"

type Vertex struct {
    X int
    Y int
}

func main() {
    v := Vertex{1, 2}
    fmt.Println(getProperty(&v, "X"))
}

func getProperty(v *Vertex, property string) (string) {
    return v[property]
}
Run Code Online (Sandbox Code Playgroud)

错误:

prog.go:18:无效操作:v [property](类型*Vertex的索引)

我想要的是使用其名称访问Vertex X属性.如果我这样做v.X,但v["X"]没有.

谁能告诉我如何使这项工作?

go go-reflect

59
推荐指数
3
解决办法
6万
查看次数

标签 统计

go ×1

go-reflect ×1