在Golang模板中使用struct方法
Go模板中的结构方法通常以与公共结构属性相同的方式调用,但在这种情况下,它不起作用: 错误:在Golang模板中使用struct方法,go,go-templates,Go,Go Templates,Go模板中的结构方法通常以与公共结构属性相同的方式调用,但在这种情况下,它不起作用: 错误: executing "person" at <.SquareAge>: SquareAge is not a field of struct type main.Person 相比之下,这项工作: {{range .}} {{.FirstName}} {{.LastName}} is {{.SquareAge}} years old. {{end}} 如何在{{with}和{{$pe
executing "person" at <.SquareAge>: SquareAge is not a field
of struct type main.Person
相比之下,这项工作:
{{range .}}
{{.FirstName}} {{.LastName}} is {{.SquareAge}} years old.
{{end}}
如何在{{with}和{{$person}}示例中调用squarage()方法?如前所述,该方法由
func (p *Person) SquareAge() int {
return p.Age * p.Age
}
仅适用于类型*个人
由于在squarage
方法中没有对Person
对象进行变异,因此只需将接收者从p*Person
更改为p Person
,即可使用上一个片段
或者,如果您更换
var people = []Person{
{"John", "Smith", 22},
{"Alice", "Smith", 25},
{"Bob", "Baker", 24},
}
与
这也行
工作示例#1:
工作示例#2:可能的重复令人惊讶的是,编译器足够聪明,可以为您添加
&Person
s,只要声明切片的类型正确:
func (p *Person) SquareAge() int {
return p.Age * p.Age
}
var people = []Person{
{"John", "Smith", 22},
{"Alice", "Smith", 25},
{"Bob", "Baker", 24},
}
var people = []*Person{
{"John", "Smith", 22},
{"Alice", "Smith", 25},
{"Bob", "Baker", 24},
}