Reputation: 815
Is it possible in go to access a struct property by its index?
For example when I have a struct of Type Person {name string, age int}
and I have a function with an index parameter, I want to be able to get the age of that struct if the index is 1 or the name if the index is 0.
I tried something like that in my code but it is not working with the error that it can not be indexed.
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
Upvotes: 1
Views: 860
Reputation: 836
As mentioned by @icza, you can use reflection, but you can simply achieve what you want by using a mapper, which is safer and cleaner like:
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)
}
If you want to use reflection:
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())
Upvotes: 4