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

我正在学习Google 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);

如果您使用签名,它将起作用。 没有指针。

 type HelloFunc func(string) func SayHello(to string) { fmt.Printf("Hello, %s!\n", to) } func main() { var hf HelloFunc hf = SayHello hf("world") } 

或者,您可以直接使用函数签名,而无需声明新的types。

Go和C和C ++没有相同的函数指针语法。 Go博客上有很好的解释。 可以理解的是,Go作者认为C函数指针的语法与常规指针类似,所以简而言之,他们决定明确指出函数指针; 即更可读。

这是我写的一个例子。 请注意在calculate()定义了fp参数,下面的另一个示例演示了如何将函数指针变成一个types并将其用于函数(注释计算函数)中。

 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提到的相同的东西,但显示了一个不同的用法示例。

你可以这样做:

 package main import "fmt" func hello(){ fmt.Println("Hello World") } func main(){ var pfunc func() pfunc = hello //pfunc is a pointer to the function "hello" pfunc() } 

如果你的函数有参数,例如返回值,它会看起来像:

 func hello(name string) int{ fmt.Println("Hello %s", name) return 0 } 

这个variables看起来像这样:

  var pfunc func(string)int