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

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

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

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

Go
皈依舞 2021-09-27 10:41:35
我正在嘗試從服務器返回一些 json,但使用以下代碼收到此錯誤cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write通過一點谷歌搜索,我找到了這個 SO 答案,但無法使其正常工作(請參閱帶有錯誤消息的第二個代碼示例)第一個代碼示例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有錯誤的第二個代碼示例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貢獻1898條經驗 獲得超8個贊

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


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


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

...或使用Buffer.WriteTo()將緩沖區內容直接復制到 a Writer:


_, err = buffer.WriteTo(w)

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


var buf []byte


buf, err = json.Marshal(thing)


_, err = w.Write(buf)


查看完整回答
反對 回復 2021-09-27
  • 2 回答
  • 0 關注
  • 515 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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