在Java中,我可以这样做
derp(new Runnable { public void run () { /* run this sometime later */ } })
然后在方法中“运行”代码。处理起来很麻烦(匿名内部类),但这是可以做到的。
Go是否有一些可以方便函数/回调作为参数传递的东西?
在Java中,我可以这样做
derp(new Runnable { public void run () { /* run this sometime later */ } })
然后在方法中“运行”代码。处理起来很麻烦(匿名内部类),但这是可以做到的。
Go是否有一些可以方便函数/回调作为参数传递的东西?
当前回答
这是我能想到的最简单的方法。
package main
import "fmt"
func main() {
g := greeting
getFunc(g)
}
func getFunc(f func()) {
f()
}
func greeting() {
fmt.Println("Hello")
}
其他回答
你也可以传递一个struct的函数,比如:
package main
// define struct
type Apple struct {}
// return apple's color
func (Apple) GetColor() string {
return "Red"
}
func main () {
// instantiate
myApple := Apple{}
// put the func in a variable
theFunc := myApple.GetColor
// execute the variable as a function
color := theFunc()
print(color)
}
输出将为“红色”,检查操场
这里有一个简单的例子:
package main
import "fmt"
func plusTwo() (func(v int) (int)) {
return func(v int) (int) {
return v+2
}
}
func plusX(x int) (func(v int) (int)) {
return func(v int) (int) {
return v+x
}
}
func main() {
p := plusTwo()
fmt.Printf("3+2: %d\n", p(3))
px := plusX(3)
fmt.Printf("3+3: %d\n", px(3))
}
是的,Go确实接受一类函数。
请参阅文章“Go中的第一类函数”以获得有用的链接。
这是我能想到的最简单的方法。
package main
import "fmt"
func main() {
g := greeting
getFunc(g)
}
func getFunc(f func()) {
f()
}
func greeting() {
fmt.Println("Hello")
}
我希望下面的例子能更清楚地说明问题。
package main
type EmployeeManager struct{
category string
city string
calculateSalary func() int64
}
func NewEmployeeManager() (*EmployeeManager,error){
return &EmployeeManager{
category : "MANAGEMENT",
city : "NY",
calculateSalary: func() int64 {
var calculatedSalary int64
// some formula
return calculatedSalary
},
},nil
}
func (self *EmployeeManager) emWithSalaryCalculation(){
self.calculateSalary = func() int64 {
var calculatedSalary int64
// some new formula
return calculatedSalary
}
}
func updateEmployeeInfo(em EmployeeManager){
// Some code
}
func processEmployee(){
updateEmployeeInfo(struct {
category string
city string
calculateSalary func() int64
}{category: "", city: "", calculateSalary: func() int64 {
var calculatedSalary int64
// some new formula
return calculatedSalary
}})
}