2 回答
TA貢獻1829條經驗 獲得超13個贊
所以這里有一個使用反射的答案,我想這不會太難看。
package main
import (
"fmt"
"reflect"
)
type onEach func(x interface{})
func printString(x interface{}) {
xx := x.(string)
fmt.Printf("x is a string '%s'\n", xx)
}
func printInt(x interface{}) {
xx := x.(int)
fmt.Printf("x is an int '%d'\n", xx)
}
func forEach(y interface{}, onEach onEach) {
// code to ensure y is a slice omitted
v := reflect.ValueOf(y)
for i := 0; i < v.Len(); i++ {
onEach(v.Index(i).Interface())
}
}
func main() {
s := []string{"foo", "bar"}
i := []int{1, 2, 3}
forEach(s, printString)
forEach(i, printInt)
}
TA貢獻1811條經驗 獲得超4個贊
使用反射包在任意類型的切片上編寫迭代函數:
// forEach calls f for each element of slice s.
// The function f must have a single argument with
// the same type as the slice's element type.
func forEach(s interface{}, f interface{}) {
sv := reflect.ValueOf(s)
fv := reflect.ValueOf(f)
for i := 0; i < sv.Len(); i++ {
fv.Call([]reflect.Value{sv.Index(i)})
}
}
像這樣使用它:
func printString(s string) {
fmt.Printf("x is a string %q\n", s)
}
s := []string{"foo", "bar"}
forEach(s, printString)
此答案與問題中的代碼和另一個答案不同,因為該函數不需要使用類型評估。f
- 2 回答
- 0 關注
- 151 瀏覽
添加回答
舉報
