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

Kev*_*vin 48 go

我正在学习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
}
Run Code Online (Sandbox Code Playgroud)

有没有办法声明函数指针而不像上面那样定义它?我们可以写一些像C一样的东西吗?

例如 void (*pfunc)(void);

the*_*mue 69

如果您使用签名,它会起作用.没有指针.

type HelloFunc func(string)

func SayHello(to string) {
    fmt.Printf("Hello, %s!\n", to)
}

func main() {
    var hf HelloFunc

    hf = SayHello

    hf("world")
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以直接使用函数签名,而无需声明新类型.


han*_*son 33

Go与C和C++没有相同的函数指针语法.在Go博客上有一个很好的解释.可以理解的是,Go的作者认为C的函数指针语法与常规指针太相似,所以简而言之,他们决定使函数指针显式化; 即更具可读性.

这是我写的一个例子.请注意fp参数的定义方式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
}
Run Code Online (Sandbox Code Playgroud)

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


Dev*_*iya 9

函数也是 Go 中的一种类型。所以你基本上可以创建一个类型func签名的变量。所以下面会起作用;

var pfunc func(string)
Run Code Online (Sandbox Code Playgroud)

该变量可以指向任何以字符串为参数且不返回任何内容的函数。以下代码运行良好。

package main

import "fmt"

func SayHello(to string) {
    fmt.Printf("Hello, %s!\n", to)
}

func main() {
    var pfunc func(string)

    pfunc = SayHello

    pfunc("world")
}
Run Code Online (Sandbox Code Playgroud)


nos*_*nos 5

您可以这样做:

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()            
}
Run Code Online (Sandbox Code Playgroud)

如果您的函数具有参数和例如返回值,则它将类似于:

func hello(name string) int{

       fmt.Println("Hello %s", name)
       return 0
}
Run Code Online (Sandbox Code Playgroud)

变量看起来像:

  var pfunc func(string)int
Run Code Online (Sandbox Code Playgroud)