为了账号安全,请及时绑定邮箱和手机立即绑定

我们可以在Go中使用函数指针吗?

我们可以在Go中使用函数指针吗?

Go
守着一只汪 2021-04-07 13:14:44
我正在学习Go语言中的指针。并设法写了像这样的东西:func hello(){       fmt.Println("Hello World")}func main(){       pfunc := hello     //pfunc is a pointer to the function "hello"       pfunc()            //calling pfunc prints "Hello World" similar to hello function}有没有一种方法可以声明函数指针而无需像上面那样定义它?我们可以像在C语言中一样编写一些东西吗?例如 void (*pfunc)(void);
查看完整描述

3 回答

?
慕森王

TA贡献1777条经验 获得超3个赞

Go对于函数指针的语法与C和C ++不同。Go博客上对此有很好的解释。可以理解,Go的作者认为C的函数指针语法与常规指针非常相似,因此简而言之,他们决定使函数指针明确。即更具可读性。


这是我写的一个例子。请注意,如何在fp中定义参数,calculate()下面的另一个示例向您展示如何将函数指针变成类型并在函数中使用它(带注释的calculate函数)。


package main


import "fmt"


type ArithOp func(int, int)int


func main() {

    calculate(Plus)

    calculate(Minus)

    calculate(Multiply)

}


func calculate(fp func(int, int)int) {

    ans := fp(3,2)

    fmt.Printf("\n%v\n", ans) 

}


// This is the same function but uses the type/fp defined above

// 

// func calculate (fp ArithOp) {

//     ans := fp(3,2)

//     fmt.Printf("\n%v\n", ans) 

// }


func Plus(a, b int) int {

    return a + b

}


func Minus(a, b int) int {

    return a - b

}


func Multiply(a,b int) int {

    return a * b

}

该fp参数定义为一个接受两个int并返回一个int的函数。这与Mue提到的有些相同,但是显示了不同的用法示例。


查看完整回答
反对 回复 2021-04-26
  • 3 回答
  • 0 关注
  • 266 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信