mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 07:02:11 +08:00
64 lines
782 B
Go
Executable File
64 lines
782 B
Go
Executable File
package main
|
|
|
|
import "fmt"
|
|
|
|
type obj interface{}
|
|
|
|
func main() {
|
|
// define a generic lambda function mf:
|
|
mf := func(i obj) obj {
|
|
switch i.(type) {
|
|
case int:
|
|
return i.(int) * 2
|
|
case string:
|
|
return i.(string) + i.(string)
|
|
}
|
|
return i
|
|
}
|
|
|
|
isl := []obj{0, 1, 2, 3, 4, 5}
|
|
res1 := mapFunc(mf, isl)
|
|
for _, v := range res1 {
|
|
fmt.Println(v)
|
|
}
|
|
println()
|
|
|
|
ssl := []obj{"0", "1", "2", "3", "4", "5"}
|
|
res2 := mapFunc(mf, ssl)
|
|
for _, v := range res2 {
|
|
fmt.Println(v)
|
|
}
|
|
}
|
|
|
|
func mapFunc(mf func(obj) obj, list []obj) []obj {
|
|
result := make([]obj, len(list))
|
|
|
|
for ix, v := range list {
|
|
result[ix] = mf(v)
|
|
}
|
|
|
|
// Equivalent:
|
|
/*
|
|
for ix := 0; ix<len(list); ix++ {
|
|
result[ix] = mf(list[ix])
|
|
}
|
|
*/
|
|
return result
|
|
}
|
|
|
|
/* Output:
|
|
0
|
|
2
|
|
4
|
|
6
|
|
8
|
|
10
|
|
|
|
00
|
|
11
|
|
22
|
|
33
|
|
44
|
|
55
|
|
*/
|