Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using struct method in Golang template

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?

like image 704
Maxim Kachurovskiy Avatar asked Dec 05 '14 22:12

Maxim Kachurovskiy


1 Answers

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

like image 65
Momer Avatar answered Nov 16 '22 09:11

Momer