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

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

如何保存呈現(xiàn)的模板而不是打印到 os.Stdout?

如何保存呈現(xiàn)的模板而不是打印到 os.Stdout?

Go
九州編程 2023-03-21 15:17:37
我是新來的。我一直在搜索文檔。在下面的游樂場代碼中,它正在屏幕上渲染和打印它。我希望將呈現(xiàn)的文本存儲在字符串中,以便我可以從函數(shù)中返回它。package mainimport (    "os"    "text/template")type Person struct {    Name string //exported field since it begins with a capital letter}func main() {    t := template.New("sammple") //create a new template with some name    t, _ = t.Parse("hello {{.Name}}!") //parse some content and generate a template, which is an internal representation    p := Person{Name:"Mary"} //define an instance with required field    t.Execute(os.Stdout, p) //merge template ‘t’ with content of ‘p’}https://play.golang.org/p/-qIGNSfJwEX怎么做 ?
查看完整描述

1 回答

?
Helenr

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊

只需將其呈現(xiàn)到內(nèi)存緩沖區(qū)中,例如bytes.Buffer(或strings.Builder在 Go 1.10 中添加),您可以通過string調(diào)用其Bytes.String()(or Builder.String()) 方法獲取其內(nèi)容:

buf := &bytes.Buffer{}

if err := t.Execute(buf, p); err != nil {

    panic(err)

}


s := buf.String()

fmt.Println(s)

這將再次打?。ㄔ贕o Playground上嘗試):

hello Mary!

但這次是s字符串變量的值。

使用strings.Builder(),你只需要改變這一行:

buf := &strings.Builder{}

在Go Playground試試這個(gè)。


查看完整回答
反對 回復(fù) 2023-03-21
  • 1 回答
  • 0 關(guān)注
  • 88 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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