5

Go 模板中的结构方法通常与公共结构属性的调用方式相同,但在这种情况下它不起作用:http ://play.golang.org/p/xV86xwJnjA

{{with index . 0}}
  {{.FirstName}} {{.LastName}} is {{.SquareAge}} years old.
{{end}}  

错误:

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

同样的问题:

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

相反,这有效:

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

如何在 {{with}} 和 {{$person}} 示例中调用 SquareAge() 方法?

4

1 回答 1

11

正如之前在从 Go 模板调用方法中回答的那样,方法定义为

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

仅适用于 type *Person

由于您没有Person在方法中更改对象,因此SquareAge您只需将接收器从 更改p *Personp Person,它就可以与您之前的切片一起使用。

或者,如果您更换

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

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

它也会起作用。

工作示例#1:http ://play.golang.org/p/NzWupgl8Km

工作示例#2:http ://play.golang.org/p/lN5ySpbQw1

于 2014-12-05T23:10:10.000 回答