go - Using methods with multiple return values -
i'm trying write template (using html/template) , passing struct has methods attached it, many of return multiple values. there way of accessing these within template? i'd able like:
package main import ( "fmt" "os" "text/template" ) type foo struct { name string } func (f foo) baz() (int, int) { return 1, 5 } const tmpl = `name: {{.name}}, ints: {{$a, $b := .baz}}{{$a}}, {{b}}` func main() { f := foo{"foo"} t, err := template.new("test").parse(tmpl) if err != nil { fmt.println(err) } t.execute(os.stdout, f) }
but doesn't work. there no way around it?
i've considered creating anonymous struct in code:
data := struct { foo int b int }{ f, 0, 0, } data.a, data.b = f.baz()
and passing in, prefer have in template. ideas? tried writing wrapper function added funcmaps never work @ all.
thanks suggestions!
you won't able call function returns 2 values in template unless 1 of values error. template guaranteed work @ runtime. there great answer explains here, if you're interested.
to solve problem need either 1) break function 2 separate getter functions can call in appropriate place in template; or 2) have function return simple struct values inside.
i can't tell better because have no idea implementation requires. foo , baz don't give many clues. ;)
here quick-n-dirty example of option one:
type foo struct { name string } func (f foo) geta() (int) { return 1 } func (f foo) getb() (int) { return 5 }
and modify template accordingly:
const tmpl = `name: {{.name}}, ints: {{.geta}}, {{.getb}}`
hopefully of help. :)
Comments
Post a Comment