go - Go 中的函数类型

标签 go

我试图理解 Go 中的函数类型,所以我尝试了以下代码。

package main

import "fmt"

func myfn1(i string) {
    fmt.Println(i)
}

func myfunc2(firstName string, lastName string) string {
    return "Hello "+ firstName + " " + lastName + "!"
}

func test(do func(string), val string) {
    do(val)
}

func test1(t func(string,string), fname string, lname string) string {
  opt := t(fname, lname)
  return opt
}

func main() {
    test(myfn1, "Aishu")
    greet := test1(myfunc2, "Aishu","S")
    fmt.Println(greet)
}

它会抛出以下错误。

  1. t(fname, lname) used as value
  2. cannot use myfunc2 (type func(string, string) string) as type func(string, string) in argument to test1

我不确定我做错了什么。

Playground

最佳答案

函数类型在 Golang Spec 中描述作为:

A function type denotes the set of all functions with the same parameter and result types.

这里明确提到相同参数和结果类型的函数

您传递给主程序的函数定义和您的函数需要的定义不同。如果你仔细看下面的函数,你已经将 t 作为参数传递给了 test1,它什么都不返回,但是你将它的值赋给了 opt,这就是为什么错误。

t(fname, lname) used as value

对于第二个错误,它说:

cannot use myfunc2 (type func(string, string) string) as type func(string, string) in argument to test1

因为如果您查看作为参数传递给 test1 的函数类型和您在 test1 中定义的参数类型是不同的。

请检查下面的工作代码。

package main

import "fmt"


func myfn1(i string) {
    fmt.Println(i)
}

func myfunc2(firstName string, lastName string) string{

return "Hello "+ firstName + " " + lastName + "!"


}

func test(do func(string), val string){
do(val)
}


func test1(t func(string,string) string, fname string, lname string) string{

  opt := t(fname,lname)
  return opt
}


func main() {
    test(myfn1, "Aishu")
     greet := test1(myfunc2, "Aishu","S")
     fmt.Println(greet)

}

Playground例子

关于go - Go 中的函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50088170/

相关文章:

concurrency - 即使独立,第二个 channel 也会导致死锁

go - 如何存储DNS记录(Go权威域名服务器)

go - Sqlx "missing destination name"通过指针获取结构标签

go - 如何使用 golang 写入已打开的 .xlsx 文件

c++ - 无法将 big.Int 从 Go 序列化为 C++

go - 如何在 Golang gRPC 中获取客户端 IP 地址和用户代理?

macos - 无法在 mac os 上使用 Go 命令行

go - 从 io.Reader 到 Go 中的字符串

go - 在 Go 中将英尺和英寸转换为厘米?

go - 重新分配 slice 参数的行为不同