Aishu
Aishu

Reputation: 1320

Function types in 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

Upvotes: 3

Views: 2714

Answers (2)

Himanshu
Himanshu

Reputation: 12685

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

Upvotes: 5

Jonathan Hall
Jonathan Hall

Reputation: 79674

You have two unrelated problems.

The first:

  1. t(fname, lname) used as value

Is that you're trying to assign the return value of t(fname, lname) to a variable, but t() doesn't return anything.

The second:

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

Is pretty self-explanatory. You're trying to pass a function that returns a string func(string, string) string, to a function that expects a function that returns nothing func(string, string).

Upvotes: 4

Related Questions