gpt4 book ai didi

go - 在 Golang 模板中使用 struct 方法

转载 作者:IT王子 更新时间:2023-10-29 01:24:43 25 4
gpt4 key购买 nike

Go 模板中的结构方法通常以与公共(public)结构属性相同的方式调用,但在这种情况下它不起作用: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 类型.

因为你不改变 Person SquareAge 中的对象方法,您可以将接收器从 p *Person 更改为至 p Person ,它可以与您之前的 slice 一起使用。

或者,如果你替换

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

关于go - 在 Golang 模板中使用 struct 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27325544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com