Go模板中的Struct方法通常被称为与公共结构属性相同的方法,但是在这种情况下它不起作用: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()方法?
如先前在从Go模板调用方法中所回答的那样,该方法由
func (p *Person) SquareAge() int {
return p.Age * p.Age
}
仅在type上可用*Person
。
由于您无需Person
在SquareAge
方法中更改对象,因此只需将接收器从更改p *Person
为p 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},
}
也可以。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句