5

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?

Maxim Kachurovskiy
  • 2,992
  • 2
  • 21
  • 24
  • possible duplicate of [Call a method from a Go template](http://stackoverflow.com/questions/10200178/call-a-method-from-a-go-template) – Momer Dec 05 '14 at 23:01

1 Answers1

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

Community
  • 1
  • 1
Momer
  • 3,158
  • 22
  • 23
  • Surprisingly, the compiler's clever enough to add the `&Person`s for you as long as the slice is declared to be of the right type: http://play.golang.org/p/FsKEUjmxPn – twotwotwo Dec 06 '14 at 03:14