-2

What I am doing

 func foo(a string) {}

 func bar(b, c string)

 type fn func(string)

 m: = map[string] fn {
     "a": "foo",
     "b": "bar"
 }

What is output

when I call function like this

  m["a"]("Hello")
  m["b"]("Hello", "World")

I got an error because type fn func(string) here fn have single parameter but I pass double parameter in m["b"]("Hello", "World")

Error : [ cannot use (type func(string, string)) as type fn in map value ]

What I am looking for

I want to make dynamic type fn func(string) so that I can pass number of parameter so that I can call like this

  m["a"]("Hello")
  m["b"]("Hello", "World")
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Manjeet Thakur
  • 2,288
  • 1
  • 16
  • 35

2 Answers2

4

Create a variadic function which will take any number of arguments as parameters on passing it to function.

 func foo(nums ...string) {}

 m:= map[string]fn{
     "a": "foo",
     "b": "bar"
 }

For more on variadic functions check this Answer

Himanshu
  • 12,071
  • 7
  • 46
  • 61
1

Solve using interface

m: = map[string]interface{} {
     "a": "foo",
     "b": "bar"
 }
Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49
Manjeet Thakur
  • 2,288
  • 1
  • 16
  • 35