Using struct method in Golang template

Struct methods in Go templates are usually named the same 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}}  

      

Mistake:

executing "person" at <.SquareAge>: SquareAge is not a field
of struct type main.Person

      

A similar problem with:

{{$person := index . 0}}
{{$person.FirstName}} {{$person.LastName}} is
  {{$person.SquareAge}} years old.

      

In constrast mode this works:

{{range .}}
  {{.FirstName}} {{.LastName}} is {{.SquareAge}} years old.
{{end}}

      

How to call the SquareAge () method in the {{with}} and {{$}} examples?

+3


source to share


1 answer


As previously stated in Call a Method from the Go Template , a method defined as

func (p *Person) SquareAge() int {
    return p.Age * p.Age
}

      

available only by type *Person

.

Since you are not mutating the object Person

in the method SquareAge

, you can simply change the receiver from p *Person

to p Person

and it will work with your previous slice.

Alternatively, if you replace

var people = []Person{
    {"John", "Smith", 22},
    {"Alice", "Smith", 25},
    {"Bob", "Baker", 24},
}

      



from

var people = []*Person{
    {"John", "Smith", 22},
    {"Alice", "Smith", 25},
    {"Bob", "Baker", 24},
}

      

It will also work.

Working example # 1: http://play.golang.org/p/NzWupgl8Km

Working example # 2: http://play.golang.org/p/lN5ySpbQw1

+6


source







All Articles