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

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

问题描述

我正在学习Google Go的指针。并设法写出类似于

  func hello(){

fmt.Println(Hello世界)
}

func main(){

pfunc:= hello // pfunc是指向函数hello的指针
pfunc ()//调用pfunc打印类似于hello函数的Hello World
}

是有没有一种方法来声明函数指针而不像上面那样定义它?
我们可以写出类似于C的东西吗?

例如。 void(* pfunc)(void);

解决方案

你正在使用签名。没有指针。
$ b $ pre $ type HelloFunc func(string)

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

func main(){
var hf HelloFunc

hf = SayHello

hf(world)
}

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


I was learning about pointers in Google 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
}

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

e.g. 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.

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

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