在Golang模板中使用struct方法
发布时间:2020-12-16 09:27:20 所属栏目:大数据 来源:网络整理
导读:Go模板中的Struct方法通常与公共结构属性的方式相同,但在这种情况下它不起作用: http://play.golang.org/p/xV86xwJnjA {{with index . 0}} {{.FirstName}} {{.LastName}} is {{.SquareAge}} years old.{{end}} 错误: executing "person" at .SquareAge: Sq
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()方法? 解决方法
正如之前在
Call a method from a Go template中所回答的那样,该方法定义如下
func (p *Person) SquareAge() int { return p.Age * p.Age } 仅适用于* Person类型. 由于您没有在SquareAge方法中改变Person对象,因此您可以将接收器从p * Person更改为p Person,它可以与之前的切片一起使用. 或者,如果您更换 var people = []Person{ {"John","Smith",22},{"Alice",25},{"Bob","Baker",24},} 同 var people = []*Person{ {"John",} 它也会起作用. 工作示例#1:http://play.golang.org/p/NzWupgl8Km 工作示例#2:http://play.golang.org/p/lN5ySpbQw1 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |