我正在学习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")
}
或者,您可以直接使用函数签名,而无需声明新类型。
Go与C和C ++没有相同的函数指针语法。在Go blog上有一个很好的解释。可以理解的是,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
}
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
}
变量看起来像:
var pfunc func(string)int
接近它的另一种方法是定义一个接口
type command interface {
DoLoop()
}
实现一个实现它的结构
type Delete struct {
instance string
}
func (dev Delete) DoLoop() {
fmt.Println("input: delete ")
}
创建包含结构的地图
mainFuncTable = make(map[string]command)
mainFuncTable["delete"] = Delete{"new"}
调用函数
func route(command string) {
cmd := mainFuncTable[command]
cmd.DoLoop()
}
这有点间接但是有效