登录
首页 >  Golang >  Go问答

多个条件下Golang文本/模板配备 "非" 运算符

来源:stackoverflow

时间:2024-02-08 14:45:23 270浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《多个条件下Golang文本/模板配备 "非" 运算符》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

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

我想检查 .hello 是否不包含“world”并且 .world 是否不包含“hello”,但我不能,因为我得到 2009/11/10 23:00:00 执行 template: template : content:2:5: 在 执行“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文本/模板配备 "非" 运算符》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>