在结构中充当成员

I am trying to make function as a member in my structure

type myStruct struct {
    myFun func(interface{}) interface{}
}
func testFunc1(b bool) bool {
    //some functionality here
    //returns a boolean at the end
}
func testFunc2(s string) int {
    //some functionality like measuring the string length
    // returns an integer indicating the length
}
func main() {
    fr := myStruct{testFunc1}
    gr := myStruct{testFunc2}
}

I am getting the error:

Cannot use testFunc (type func(b bool) bool) as type func(interface{}) interface{}
Inspection info: Reports composite literals with incompatible types and values.

I am unable to figure out why I am getting this error.

Your code's problem is the incompatible types between the declaration in the struct and testFunc. A function taking interface{} and returning interface{} doesn't have the same type as a function taking and returning bool, so the initialization fails. The compiler error message you pasted is right on point here.


This will work:

package main

type myStruct struct {
    myFun func(bool) bool
}

func testFunc(b bool) bool {
    //some functionality here
    //returns a boolean at the end
    return true
}

func main() {
    fr := myStruct{testFunc}
}