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

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

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

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

立即学习go语言免费学习笔记(深入)”;

Tellers AI
Tellers AI

Tellers是一款自动视频编辑工具,可以将文本、文章或故事转换为视频。

Tellers AI 78
查看详情 Tellers AI

解决方法

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

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号