go - Using struct method in Golang template -


struct methods in go templates called same way public struct properties in case doesn't work: http://play.golang.org/p/xv86xwjnja

{{with index . 0}}   {{.firstname}} {{.lastname}} {{.squareage}} years old. {{end}}   

error:

executing "person" @ <.squareage>: squareage not field of struct type main.person 

same problem with:

{{$person := index . 0}} {{$person.firstname}} {{$person.lastname}}   {{$person.squareage}} years old. 

in constrast, works:

{{range .}}   {{.firstname}} {{.lastname}} {{.squareage}} years old. {{end}} 

how call squareage() method in {{with}} , {{$person}} examples?

as answered in call method go template, method defined by

func (p *person) squareage() int {     return p.age * p.age } 

is available on type *person.

since don't mutate person object in squareage method, change receiver p *person p person, , work previous slice.

alternatively, if replace

var people = []person{     {"john", "smith", 22},     {"alice", "smith", 25},     {"bob", "baker", 24}, } 

with

var people = []*person{     {"john", "smith", 22},     {"alice", "smith", 25},     {"bob", "baker", 24}, } 

it'll work well.

working example #1: http://play.golang.org/p/nzwupgl8km

working example #2: http://play.golang.org/p/ln5yspbqw1


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -