2 回答

TA貢獻1877條經驗 獲得超1個贊
使用Value.Len和Value.Index迭代數組或切片:
func processData(l LotsOfSlices) {
v := reflect.ValueOf(l)
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
if f.Kind() != reflect.Slice {
continue
}
for i := 0; i < f.Len(); i++ {
e := f.Index(i)
s := e.FieldByName("F")
// Do something with s
}
}
}

TA貢獻1842條經驗 獲得超22個贊
如果您的結構執行類似的最終結果(返回 int 或對字符串進行操作)但對于每種結構類型都是唯一的,您可以在它們上定義函數:
func (a *A) GetResult() int { // sums two numbers
return a.p1 + a.p2
}
func (b *B) GetResult() int { // subtracts two numbers
return b.p1 - b.p2
}
func (c *C) GetResult() int { // times two numbers
return c.p1 * c.p2
}
然后定義一個接口Operable
type Operable interface {
GetResult() int // shared function
}
然后創建一個接受接口作為參數的函數,并且任何實現該接口中所有函數的結構都可以作為參數被接受
func processOperable(o []Operable){
for _, v := range o{
v.GetResult() --> unique for each struct
}
}
- 2 回答
- 0 關注
- 136 瀏覽
添加回答
舉報