亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

將執行文本/模板模板的結果分配到變量中

將執行文本/模板模板的結果分配到變量中

Go
慕森卡 2022-08-24 16:17:36
type Inventory struct {    Material string    Count    uint}sweaters := Inventory{"wool", 17}tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")err = tmpl.Execute(os.Stdout, sweaters)如何將模板執行的結果保存在 golang 變量中,而不是寫入 。os.Stdout
查看完整描述

1 回答

?
心有法竹

TA貢獻1866條經驗 獲得超5個贊

正如您在此處看到的 https://golang.org/pkg/text/template/#Template.Execute,execute方法中有一個arg,因此您可以傳遞任何io.Writerio.Writer


我希望這會有所幫助。https://play.golang.org/p/kXRQ7G3uO20


package main


import (

    "fmt"

    "bytes"

    "text/template"

)


type Inventory struct {

    Material string

    Count    uint

}



func main() {

    var buf bytes.Buffer

    sweaters := Inventory{"wool", 17}

    tmpl, _ := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")

    _ = tmpl.Execute(&buf, sweaters)

    

    s := buf.String()

    fmt.Println(s)

}


查看完整回答
反對 回復 2022-08-24
  • 1 回答
  • 0 關注
  • 65 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號