如何将“或”运算符与多个比较参数一起使用,或者有什么想法可以找到一些示例?官方文档上好像没有。
if (x == "value" && y == "other") || (x != "a") && (y == "b"){
print("hello")
}
Run Code Online (Sandbox Code Playgroud)
官方文档确实对 for or、and、eq和neqfor 在模板中的使用进行了解释。您可以在此处阅读有关模板函数的信息。
要记住的是,模板中提供的函数是前缀表示法(波兰表示法)。例如, ne 1 2鉴于两个参数 1 和 2 不相等,不等于运算符的计算结果将为 true。以下是一个模板示例,该模板使用以模板函数为前缀重写的给定表达式。
package main
import (
"os"
"text/template"
)
type Values struct {
Title, X, Y string
}
func main() {
// Parenthesis are used to illustrate order of operation but could be omitted
const given_template = `
{{ if or (and (eq .X "value") (eq .Y "other")) (and (ne .X "a") (eq .Y "b")) }}
print("hello, {{.Title}}")
{{end}}`
values := []Values{
Values{Title: "first", X: "value", Y: "other"},
Values{Title: "second", X: "not a", Y: "b"},
Values{Title: "neither", X: "Hello", Y: "Gopher"},
}
t := template.Must(template.New("example").Parse(given_template))
for _, value := range values {
err := t.Execute(os.Stdout, &value)
if err != nil {
panic(err)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15199 次 |
| 最近记录: |