golang 返回函数的匿名函数 vs 接收器的方法


返回函数的匿名函数:



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main
import "fmt"
type Point struct{ X, Y float64 }
func main() {
f := func(p Point) func () int {
var x int
return func () int {
x++
return x * x
}
}
p := Point{1, 2}
g:=f(p)
fmt.Println("result:",g())
fmt.Println("result:",g())
}


result: 1
result: 4



接收器的方法:



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main
import (
"fmt"
"reflect"
)

type Point struct{ X, Y float64 }
func(p Point) NewF () int {
return 1
}
func main() {
p := Point{1, 2}
fmt.Println(reflect.TypeOf(p.NewF))
fmt.Println(reflect.TypeOf(Point.NewF(p)))
}


func() int
int


Category golang