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

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

如何轉(zhuǎn)換(類型 *bytes.Buffer)以用作 w.Write 的參數(shù)中的 []byte

如何轉(zhuǎn)換(類型 *bytes.Buffer)以用作 w.Write 的參數(shù)中的 []byte

Go
皈依舞 2021-09-27 10:41:35
我正在嘗試從服務(wù)器返回一些 json,但使用以下代碼收到此錯(cuò)誤cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write通過(guò)一點(diǎn)谷歌搜索,我找到了這個(gè) SO 答案,但無(wú)法使其正常工作(請(qǐng)參閱帶有錯(cuò)誤消息的第二個(gè)代碼示例)第一個(gè)代碼示例buffer := new(bytes.Buffer)for _, jsonRawMessage := range sliceOfJsonRawMessages{    if err := json.Compact(buffer, jsonRawMessage); err != nil{        fmt.Println("error")    }}   fmt.Println("json returned", buffer)//this is jsonw.Header().Set("Content-Type", contentTypeJSON)w.Write(buffer)//error: cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write有錯(cuò)誤的第二個(gè)代碼示例cannot use foo (type *bufio.Writer) as type *bytes.Buffer in argument to json.Compact cannot use foo (type *bufio.Writer) as type []byte in argument to w.Writevar b bytes.Bufferfoo := bufio.NewWriter(&b)for _, d := range t.J{    if err := json.Compact(foo, d); err != nil{        fmt.Println("error")    }}w.Header().Set("Content-Type", contentTypeJSON)w.Write(foo)
查看完整描述

2 回答

?
汪汪一只貓

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

Write 需要一個(gè)[]byte(字節(jié)片),并且您有一個(gè)*bytes.Buffer(指向緩沖區(qū)的指針)。


您可以使用Buffer.Bytes()從緩沖區(qū)獲取數(shù)據(jù)并將其提供給Write():


_, err = w.Write(buffer.Bytes())

...或使用Buffer.WriteTo()將緩沖區(qū)內(nèi)容直接復(fù)制到 a Writer:


_, err = buffer.WriteTo(w)

使用 abytes.Buffer并不是絕對(duì)必要的。 json.Marshal()[]byte直接返回一個(gè):


var buf []byte


buf, err = json.Marshal(thing)


_, err = w.Write(buf)


查看完整回答
反對(duì) 回復(fù) 2021-09-27
  • 2 回答
  • 0 關(guān)注
  • 517 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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