dongren5293 2018-04-29 15:19
浏览 96
已采纳

Go中的函数类型

I'm trying to understand function types in Go, so I tried with the below code.

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)
}

And it throws below error.

  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

I'm not sure what I'm doing wrong.

Playground

  • 写回答

2条回答 默认 最新

  • dongwenhui8900 2018-04-29 15:29
    关注

    Function types are described in Golang Spec as:

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

    Here it is clearly mentioned that function with same parameter and result types

    There are different functions definition that you are passing to your main program and the definitions that your function requires. If you look at below function carefully you have passed t as argument to test1 which returns nothing but you are assign its value to opt that's why the error.

    t(fname, lname) used as value

    For second error which says:

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

    Since because if you look at the type of function you are passing to test1 as an argument and the type of argument that you have defined in test1 are different.

    Please check below working code.

    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 example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!