Struct methods in Go templates are usually called same way as public struct properties but in this case it just doesn't work: http://play.golang.org/p/xV86xwJnjA
{{with index . 0}}
{{.FirstName}} {{.LastName}} is {{.SquareAge}} years old.
{{end}}
Error:
executing "person" at <.SquareAge>: SquareAge is not a field
of struct type main.Person
Same problem with:
{{$person := index . 0}}
{{$person.FirstName}} {{$person.LastName}} is
{{$person.SquareAge}} years old.
In constrast, this works:
{{range .}}
{{.FirstName}} {{.LastName}} is {{.SquareAge}} years old.
{{end}}
How to call SquareAge() method in {{with}} and {{$person}} examples?
As previously answered in Call a method from a Go template, the method as defined by
func (p *Person) SquareAge() int {
return p.Age * p.Age
}
is only available on type *Person
.
Since you don't mutate the Person
object in the SquareAge
method, you could just change the receiver from p *Person
to p Person
, and it would work with your previous slice.
Alternatively, if you 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 as well.
Working example #1: http://play.golang.org/p/NzWupgl8Km
Working example #2: http://play.golang.org/p/lN5ySpbQw1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With