
php小编西瓜向大家介绍Golang中一个有趣的特性——文本/模板带有!not运算符的多个条件。这个特性在Golang的模板引擎中非常实用,能够帮助我们更灵活地处理条件判断。通过使用!not运算符,我们可以在模板中同时判断多个条件,简化代码逻辑,提高开发效率。本文将详细介绍如何使用这个特性,并给出一些使用示例,帮助大家更好地理解和应用。让我们一起来探索这个有趣的Golang特性吧!
如何在 Go 中使用间接模板函数链接多个条件?
我想检查 .hello 是否不包含“world”并且 .world 是否不包含“hello”,但我不能,因为我得到 2009/11/10 23:00:00 执行 template: template : content:2:5: 在 <not> 执行“content”:not 的参数数量错误:want 1 收到 2 错误消息
package main
import (
"log"
"os"
"strings"
"text/template"
)
var (
templateFuncMap = template.FuncMap{
"contains": strings.Contains,
}
)
func main() {
// Define a template.
const temp = `
{{if not (contains .hello "hello") (contains .world "hello") }}
passed
{{else}}
not passed
{{end}}`
s := map[string]string{
"hello": "world",
"world": "hello",
}
t := template.Must(template.New("content").Funcs(templateFuncMap).Parse(temp))
err := t.Execute(os.Stdout, s)
if err != nil {
log.Println("executing template:", err)
}
}
去游乐场链接:https://go.dev/play/p/lWZwjbnSewy
立即学习“go语言免费学习笔记(深入)”;
not 需要一个参数,因此必须使用括号。
如果这样做,您要否定的条件是 contains "hello" 或 contains "world":
{{if not (or (contains .hello "hello") (contains .world "hello")) }}这将输出(在 Go Playground 上尝试):
not passed
您也可以将此条件写为 not contains "hello" and not contains "world", 如下所示:
{{if and (not (contains .hello "hello")) (not (contains .world "hello")) }}以上就是Golang 文本/模板带有 !not 运算符的多个条件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号