登录
首页 >  Golang >  Go问答

Go - 通过索引访问结构体属性

来源:stackoverflow

时间:2024-04-02 11:42:36 470浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《Go - 通过索引访问结构体属性》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

go 中是否可以通过索引访问结构体属性?

例如,当我有一个类型为 person {name string,age int} 的结构时

我有一个带有索引参数的函数,我希望能够在索引为 1 时获取该结构的年龄,或者在索引为 0 时获取该结构的名称。

我在代码中尝试了类似的操作,但它无法正常工作,并出现无法索引的错误。

func filterOHLCV(candles []*binance.Kline, index OHLCV_INDEX) []float64 {
close := []float64{}
for _, c := range candles {
    closePrice, err := strconv.ParseFloat(c[index], 64)
    if err != nil {
        fmt.Print(err)
    }
    close = append(close, closePrice)}

return close

正确答案


正如@icza所提到的,您可以使用反射,但您可以通过使用映射器来简单地实现您想要的,这更安全、更干净,例如:

type myindex int

const (
    nameindex myindex = iota
    ageindex
    // other properties here
)

type person struct {
    name string
    age  int
}

func filterpersonproperty(persons []person, index myindex) []interface{} {
    result := []interface{}{}
    for _, p := range persons {
        if index == nameindex {
            result = append(result, p.name)
        } else if index == ageindex {
            result = append(result, p.age)
        }
    }
    return result
}

func main() {
    persons := []person{
        {name: "alice", age: 30},
        {name: "bob", age: 25},
    }

    index := ageindex

    properties := filterpersonproperty(persons, index)
    fmt.println(properties)
}

如果你想使用反射:

p := Person{Name: "Alice", Age: 30}
index := []int{0} // 0 for Name, 1 for Age

value := reflect.ValueOf(p)
fieldValue := value.FieldByIndex(index)

fmt.Println(fieldValue.Interface())

以上就是《Go - 通过索引访问结构体属性》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>