英文:
Parameter to Go custom template function
问题
请看 https://play.golang.org/p/EbWA15toVa9
我在其中:
- 在第25行定义了
func iterate(count int) []int
- 在第15行调用了
iterate 5
这一切都没问题,但是,当我在第20行调用 iterate (printf "%d" 3)
时,我得到了以下错误:
template: t:12:39: 执行“t”时出错 <3>: 错误的值类型;期望 int,得到 string
难道不应该先执行 (printf "%d" 3)
,然后在传递给 iterate
时变成 iterate 3
吗?为什么会出现上述错误?
完整的代码如下:
package main
import (
"log"
"os"
"text/template"
)
var x = `{{define "t1"}}
{{- index . 0}} {{index . 1}} {{index . 2}} {{index . 3}}
{{end -}}
hello, {{template "t1" args . 543 false 0.1234}}
{{- range $val := iterate 5 }}
{{ $val }}
{{- end }}
{{ (printf "%d" 3) }}
{{- range $val := iterate (printf "%d" 3) }}
{{ $val }}
{{- end }}
`
func iterate(count int) []int {
var i int
var Items []int
for i = 0; i < (count); i++ {
Items = append(Items, i)
}
return Items
}
func args(vs ...interface{}) []interface{} { return vs }
func main() {
t := template.Must(template.New("t").Funcs(template.FuncMap{"args": args, "iterate": iterate}).Parse(x))
err := t.Execute(os.Stdout, "foobar")
if err != nil {
log.Fatal(err)
}
}
英文:
Please take a look at https://play.golang.org/p/EbWA15toVa9
in which I
- define
func iterate(count int) []int
on line 25 - call it with
iterate 5
on line 15
That's all OK, but, when call it with iterate (printf "%d" 3)
on line 20, I got the error of:
template: t:12:39: executing "t" at <3>: wrong type for value; expected int; got string
Wouldn't the (printf "%d" 3)
get executed first and when passed to iterate
, it'll become iterate 3
? Why the above error instead?
Full code enclosed:
package main
import (
"log"
"os"
"text/template"
)
var x = `{{define "t1"}}
{{- index . 0}} {{index . 1}} {{index . 2}} {{index . 3}}
{{end -}}
hello, {{template "t1" args . 543 false 0.1234}}
{{- range $val := iterate 5 }}
{{ $val }}
{{- end }}
{{ (printf "%d" 3) }}
{{- range $val := iterate (printf "%d" 3) }}
{{ $val }}
{{- end }}
`
func iterate(count int) []int {
var i int
var Items []int
for i = 0; i < (count); i++ {
Items = append(Items, i)
}
return Items
}
func args(vs ...interface{}) []interface{} { return vs }
func main() {
t := template.Must(template.New("t").Funcs(template.FuncMap{"args": args, "iterate": iterate}).Parse(x))
err := t.Execute(os.Stdout, "foobar")
if err != nil {
log.Fatal(err)
}
}
答案1
得分: 3
你是正确的,printf "%d" 3
会首先被评估。问题似乎是printf "%d" 3
生成了一个字符串,但是你的iterate
函数的参数类型是int
。这个字符串
不会被转换。
英文:
You are correct that the printf “%d” 3
gets evaluated first. The problem seems to be that printf “%d” 3
produces a string, but your iterate
function has an argument of type int
. The string
will not be converted.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论