我需要以許多不同的方式在長數組中計算元素。下面是特殊情況的用例示例:func main() { test := []test{test{"A", "1", "$"}, test{"A", "2", "€"}, test{"B", "3", "$"}} countA := 0 countDollar := 0 countADollar := 0 for _, e := range test { if e.prop1 == "A" { countA++ } if e.prop3 == "$" { countDollar++ } if e.prop1 == "A" && e.prop3 == "$" { countADollar++ } } fmt.Printf("countA: %v, count$: %v, countA$: %v\n", countA, countDollar, countADollar)}這將打印計數A: 2, 計數$: 2, 計數A$: 1https://play.golang.org/p/R0nhwFpyN7H現在的問題是:有沒有辦法對此進行泛化,以便我可以在數組的一次迭代中根據屬性計算不同的總和,而無需單獨實現每種情況?編輯2:這是一個基于用戶Volker建議的稍微好一點的版本:package mainimport "fmt"type test struct { prop1 string prop2 string prop3 string}func count2(data []test, f func(test) bool) { count1 := 0; for _, e := range data { if f(e) { count1++ } } fmt.Printf("count1: %v", count1)}func main() { data := []test{test{"A", "1", "$"}, test{"A", "2", "€"}, test{"B", "3", "$"}} myTestCrit := func(t test) bool { return t.prop1 == "A" } count2(data, myTestCrit)}https://play.golang.org/p/kB60gJCBkyn編輯3:這是一個進一步的推廣,接受多個計數器。感謝Volker和Eli的投入。也許這些來源對其他人也有用。func count3(data []test, f []func(test) bool) { counts := make([]int, len(f)); for _, e := range data { for i, fi := range f { if fi(e) { counts[i]++ } } } fmt.Printf("counts: %v\n", counts)}func main() { data := []test{test{"A", "1", "$"}, test{"A", "2", "€"}, test{"B", "3", "$"}} myTestCrit := func(t test) bool { return t.prop1 == "A" } myTestCritDollar := func(t test) bool { return t.prop3 == "$" } countCrits := make([]func(t test) bool, 2) countCrits[0] = myTestCrit countCrits[1] = myTestCritDollar count3(data, countCrits)}編輯:我也愿意接受關于如何改進問題的建議。這是我遇到的一個合法問題,一般方法將大大簡化我的代碼。
1 回答

ABOUTYOU
TA貢獻1812條經驗 獲得超5個贊
Go中沒有特別的醬汁可以做到這一點。您需要在切片上編寫一個循環 - 沒關系。
您的原始代碼絕對沒問題,特別是如果您需要在同一循環中執行多個不同的計數。該函數也很好,它抽象出一些代碼(雖然不多),但它只對單個計數器有用 - 單個過濾器/測試函數。count2
你可以繼續推廣它,例如,傳入一個結構切片,其中每個結構都是:Metrics
type Metrics struct {
Counter int
Filter func(test) bool
}
這完全取決于您的確切需求。
如果你在這里尋找慣用的Go方式:不要太擔心過早的抽象。編寫最清晰/最易讀的代碼來解決眼前的任務。
- 1 回答
- 0 關注
- 107 瀏覽
添加回答
舉報
0/150
提交
取消