i want specify function based on string. i'm getting strings out of map, in example below values in function
while interating ove map. example, when string value function
== "networkinfo", "treat" value real functions' name. it's hard explain, think guys know mean.
my goal remove switch statement , directly call c.addfunc(spec, func() { networkinfo() })
networkinfo function name, extracted string function
. know possible, don't know how :(. appreciated!
// schedulecronjobs starts scheduler func schedulecronjobs() { tasks := props.p.getstringmapstring("tasks") log.infof("number of tasks: %d", len(tasks)) if len(tasks) != 0 { c := cron.new() // each task, initialize function, spec := range tasks { switch function { case "networkinfo": c.addfunc(spec, func() { networkinfo() }) case "bla": c.addfunc(spec, func() { bla() }) default: log.errorf("unknown task: %q", function) } } c.start() } // after initialization, send out confirmation message slack.sendmessage("tasks initialized", props.p.getstring("channel")) }
why not like:
taskdefs := map[string]func(){ "networkinfo": networkinfo, "bla": bla, } function, spec := range tasks { if fn, ok := taskdefs[function]; ok { c.addfunc(spec, func() { fn() }) // not sure if need enclosing func } else { log.errorf("unknown task: %q", function) } }
if need varying signatures of funcs you'd need reflection, if types of funcs same, using map approach might simpler solution, without overhead of reflection.
the way i've found find functions name in package parsing source files. this repo example of finding funcs , storing them in map name key.
the go linker silently drop unreferenced funcs, if way you're referencing func through reflection break. why map approach suggest superior; let's linker know func being used.
Comments
Post a Comment