我们可以在Go中使用函数指针吗? [英] Can we have function pointers in Go?

查看:46
本文介绍了我们可以在Go中使用函数指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Go语言中的指针.并成功编写了类似的内容:

I was learning about pointers in Go. And managed to write something like:

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语言中一样编写一些东西吗?

Is there a way to declare the function pointer without defining it as done above? Can we write something like we do in C?

例如 void(* pfunc)(void);

推荐答案

如果您使用签名,则可以使用.没有指针.

It works if you're using the signature. There's no pointer.

type HelloFunc func(string)

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

func main() {
    var hf HelloFunc

    hf = SayHello

    hf("world")
}

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

Alternatively you can use the function signature directly, without declaring a new type.

这篇关于我们可以在Go中使用函数指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆