首頁  >  文章  >  後端開發  >  Golang 文字/範本帶有 !not 運算子的多個條件

Golang 文字/範本帶有 !not 運算子的多個條件

WBOY
WBOY轉載
2024-02-09 16:12:22411瀏覽

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刪除