第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 go 模板中通過字段名動態(tài)訪問結(jié)構(gòu)值

在 go 模板中通過字段名動態(tài)訪問結(jié)構(gòu)值

Go
慕無忌1623718 2022-06-27 15:39:48
有沒有辦法通過 go 模板中的字段名動態(tài)訪問結(jié)構(gòu)值?對于此代碼(https://play.golang.org/p/1B1sz0gnbAi):package mainimport (    "fmt"    "os"    "text/template")type Context struct {    Key string}func main() {    var context = Context{Key: "value"}    // Success    var text = `{{ .Key }}`    t := template.Must(template.New("success").Parse(text))    _ = t.Execute(os.Stdout, context)    fmt.Println("")        // Fail    text = `{{- $key := "Key" }}{{ .$key}}`    t = template.Must(template.New("fail").Parse(text))    err := t.Execute(os.Stdout, context)    if err != nil {        fmt.Println("executing template:", err)    }}我得到這個輸出:valuepanic: template: fail:1: unexpected bad character U+0024 '$' in commandgoroutine 1 [running]:text/template.Must(...)    /usr/local/go-faketime/src/text/template/helper.go:23main.main()    /tmp/sandbox897259471/prog.go:26 +0x46b我知道如何為地圖執(zhí)行此操作,我只會使用索引函數(shù)。但這不適用于結(jié)構(gòu),并且我沒有靈活性來更改作為上下文傳遞的基礎(chǔ)類型。有任何想法嗎?
查看完整描述

1 回答

?
HUH函數(shù)

TA貢獻1836條經(jīng)驗 獲得超4個贊

即使在常規(guī)的 golang 代碼中,按名稱訪問結(jié)構(gòu)字段也需要反射,因此在模板中也不是那么容易。沒有允許它的內(nèi)置函數(shù),我也不知道有任何庫提供這樣的功能。您可以做的是自己實現(xiàn)該功能。一個非?;镜膶崿F(xiàn)可能如下:


package main


import (

    "fmt"

    "os"

    "text/template"

    "reflect"

)


type Context struct {

    Key string

}


func FieldByName(c Context, field string) string {

    ref := reflect.ValueOf(c)

    f := reflect.Indirect(ref).FieldByName(field)

    return string(f.String())

}


func main() {


    context := Context{Key: "value"}

    text := `{{- $key := "Key" }}{{ fieldByName . $key}}`

    

    // Custom function map

    funcMap := template.FuncMap{

        "fieldByName": FieldByName,

    }

    // Add custom functions using Funcs(funcMap)

    t := template.Must(template.New("fail").Funcs(funcMap).Parse(text))

    

    err := t.Execute(os.Stdout, context)

    if err != nil {

        fmt.Println("executing template:", err)

    }

}



查看完整回答
反對 回復(fù) 2022-06-27
  • 1 回答
  • 0 關(guān)注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號