reflection - how do you log function call return values in golang -
i want know return values @ time of exit golang function. golang defer mechanism helpful, evaluates arguments @ time defer statement registered rather when executed. can work using anonymous function accesses return values:
func try() (int i) { defer func() {fmt.printf("%d", i)}() = 10 return i+1 } func main() { try() }
this work ok, think, handle in generic manner, perhaps like:
func try(in string) (out int) { enter("%s", in);exit("%d", out) }
or, better, use reflection output arguments/return values @ time of entry/exit. i'm assuming runtime performance isn't critical :).
is there way this? shaba abhiram's handy tracey lib go long way towards stops short of printing return values.
you correct in assesing arguments deferred function evaluated @ point defer queued, not when executed.
your method of making anonymous function refers named returns valid. approach pass in address of return values:
func try() (i int) { defer printreturns(time.now(), &i) time.sleep(10 * time.millisecond) = 10 return + 1 } func printreturns(start time.time, rets ...interface{}) { fmt.println(time.now().sub(start)) _,ret := range rets{ fmt.println(ret) } }
the problem approach logging function has pointer instead of real type , must unwrap pointers them. if using reflect
, not horribly difficult.
Comments
Post a Comment