0

I have been able to make a function map for methods without a receiver argument. Here is an example.

var funcMap = map[string]func() bool {
    "&" : And,
}

func And() bool {
    return true && false
}

But if my function has a receiver argument how could I add it to a function map? The below code does not work but tries to show what I want to do.

type Operand struct {
    Operator string
    Arg1 interface{}
    Arg2 interface{}
}

var funcMap = map[string]Operand.func() bool {
    "&" : Operand.And,
}

func (o *Operand) And() bool {
    return argToBool(o.Arg1) && argToBool(o.Arg2)
}
Uberswe
  • 1,038
  • 2
  • 16
  • 36
  • @super I believe that question is asking something a bit different from what I want to do. One option I could use is to use reflection as provided in the answer in the question linked. However I think my question is different and the answer provided by kashyap-kn is a better solution for this use case. – Uberswe Jun 21 '20 at 15:20
  • I would say at that point it's just a matter of preference. Either you have a function of signature `func(Operand*) bool` which you can wrap in an interface, or you have an interface that wraps a worker func and two arguments. In the end they are basically the same thing. – super Jun 21 '20 at 16:21
  • The advantage of the dupe is that it shows the 2 idiomatic golang approaches to binding a function with a receiver. Either implicitly bound or converted to a function that takes the receiver as it's first argument. Both supported by the language core functionality. – super Jun 21 '20 at 16:25

2 Answers2

1

Instead of creating a map with function, we can create a struct with function and its arguments

// Create a function type which takes desired params and return type
type myFunc func(interface{}, interface{})(bool) // Assuming return type as bool

// Create a struct
type workerStruct struct {
     WorkFunc   myFunc
     Arg1       interface{}
     Arg2       interface{}
}

Using above struct with function and arguments as value of the map

funcMap := map[string]workerStruct{}

myStruct := workerStruct {
    WorkFunc : Operand,           // This would your input function
    Arg1     : myarg1,
    Arg2     : myarg2,
}

funcMap["&"] = myStruct

Hope this helps

Kashyap KN
  • 399
  • 3
  • 8
0

You just need to initialise your struct:

o := Operand{
    Arg1: false,
    Arg2: true,
}

var funcMap = map[string]func() bool {
    "&" : o.And,
}
oren
  • 3,159
  • 18
  • 33