Using struct method in Golang template
Asked Answered
S

1

6

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?

Sacker answered 5/12, 2014 at 22:15 Comment(1)
possible duplicate of Call a method from a Go templateRennold
R
13

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

Rennold answered 5/12, 2014 at 23:10 Comment(1)
Surprisingly, the compiler's clever enough to add the &Persons for you as long as the slice is declared to be of the right type: play.golang.org/p/FsKEUjmxPnFlemings

© 2022 - 2024 — McMap. All rights reserved.