首页 > 后端开发 > Golang > 正文

Golang 文本/模板带有 !not 运算符的多个条件

WBOY
发布: 2024-02-09 16:12:22
转载
435 人浏览过

Golang 文本/模板带有 !not 运算符的多个条件

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

解决方法

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中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!