首页  >  文章  >  后端开发  >  Golang 文本/模板带有 !not 运算符的多个条件

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

WBOY
WBOY转载
2024-02-09 16:12:22413浏览

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

php小编西瓜向大家介绍Golang中一个有趣的特性——文本/模板带有!not运算符的多个条件。这个特性在Golang的模板引擎中非常实用,能够帮助我们更灵活地处理条件判断。通过使用!not运算符,我们可以在模板中同时判断多个条件,简化代码逻辑,提高开发效率。本文将详细介绍如何使用这个特性,并给出一些使用示例,帮助大家更好地理解和应用。让我们一起来探索这个有趣的Golang特性吧!

问题内容

如何在 Go 中使用间接模板函数链接多个条件?

我想检查 .hello 是否不包含“world”并且 .world 是否不包含“hello”,但我不能,因为我得到 2009/11/10 23:00:00 执行 template: template : content:2:5: 在 238ee6817c12cd3b0f999d2fed793ff9 执行“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删除