go语言的匿名函数
没什么好说的, 见一个,熟悉一个:
package main
import (
"fmt"
)
func main() {
func() {
fmt.Printf("func 1\n")
}()
func(x int) {
fmt.Printf("func 2, x is %d\n", x)
}(2)
a := func(x int) int {
fmt.Printf("func 3, x is %d\n", x)
return 5
}
fmt.Println(a(3))
fmt.Printf("%T\n", func() {
fmt.Printf("func 1\n")
})
fmt.Printf("%T\n", func(x int) {
fmt.Printf("func 2, x is %d\n", x)
})
fmt.Printf("%T\n", a)
}
结果:
func 1
func 2, x is 2
func 3, x is 3
5
func()
func(int)
func(int) int
继续看:
package main
import (
"fmt"
)
func main() {
test(func(x string) {
fmt.Println(x)
})
}
func test(f func(string)) {
f("hello")
}
结果:hello
但如下都错误, 想想为什么:
package main
import (
"fmt"
)
func main() {
func() {
fmt.Printf("func 1\n")
}
}
package main
import (
"fmt"
)
func main() {
test(func g(x string) {
fmt.Println(x)
})
}
func test(f func(string)) {
f("hello")
}
最后, 看看下面三个正确程序的:
package main
import (
"fmt"
)
var x = "hello"
func main() {
test(func (x *string) {
*x = "world"
})
fmt.Println(x)
}
func test(f func(*string)) {
}
package main
import (
"fmt"
)
func main() {
var s1 = "hello"
var s2 = "world"
test(func(x *string, y *string) {
*x += "_123"
*y += "_456"
}, &s1, &s2)
fmt.Println(s1, s2) // hello_123 world_456
}
func test(f func(*string, *string), s1 *string, s2 *string) {
f(s1, s2)
}
package main
import (
"fmt"
)
var s1 = "hello"
var s2 = "world"
func main() {
test(func(x *string, y *string) {
*x += "_123"
*y += "_456"
})
fmt.Println(s1, s2) // hello_123 world_456
}
func test(f func(*string, *string)) {
f(&s1, &s2)
}
不多说。