S
S
Salim_Gareev2018-04-08 10:52:44
go
Salim_Gareev, 2018-04-08 10:52:44

Call a function with the name of the function in a string?

Good afternoon.
How can you call a function knowing the name of the function? Those. the string variable contains the name of this function. Is it possible?

func f(){
fmt.Println("функция вызвана")
}

func main(){
str = "f"
вызвать_функцию(str)
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Papa, 2018-04-08
@Salim_Gareev

In general, no.
https://mikespook.com/2012/07/function-call-by-nam...

C
chromimon, 2018-04-08
@chromimon

You can only organize it through the ass. Stifler 's dad in a nearby answer showed how. A lot of reflection in the example code and shows that this is the wrong way. Only as a last resort.
And here is a thing that does not contradict the ideology of Go - it will be with an explicit indication of types:

package main

import (
  "fmt"
)

func add(a, b int) int {
  return a + b
}

func sub(a, b int) int {
  return a - b
}

func main() {

  table:= make(map[string]func(int,int)int)
  
  table["func1"] = add
  table["func2"] = sub
  
  fmt.Println(table["func1"](5, 3))
  fmt.Println(table["func2"](5, 3))
}

Much less code, types are rigidly defined.

R
Roman, 2018-04-09
@KirEv

in my opinion, when in such languages ​​they try to call a function implicitly, something is wrong with the architecture of the program.
interesting to see the full picture of what it is for.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question