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

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

json.Marshal 與 Encoder.Encode

json.Marshal 與 Encoder.Encode

Go
慕的地8271018 2022-06-13 10:30:31
在下面的代碼中:package mainimport (    "bytes"    "encoding/json"    "fmt")type Student struct {    Firstname, lastname string    Email               string    Age                 int    HeightInMeters      float64    IsMale              bool}func main() {    john := Student{        Firstname:      "John",        lastname:       "Doe",        Age:            21,        HeightInMeters: 1.75,        IsMale:         true,    }    johnJSON, _ := json.Marshal(john) // johnJSON is of type []byte    fmt.Println(string(johnJSON))     // print it in characters}johnJSON, _ := json.Marshal(john)john正在將 struct type( )編碼為[]byte.在下面的代碼中:package mainimport (    "bytes"    "encoding/json"    "fmt")type Student struct {    Firstname, lastname string    Email               string    Age                 int    HeightInMeters      float64    IsMale              bool}func main() {    john := Student{        Firstname:      "John",        lastname:       "Doe",        Age:            21,        HeightInMeters: 1.75,        IsMale:         true,    }    // johnJSON, _ := json.Marshal(john) // johnJSON is of type []byte    // fmt.Println(string(johnJSON))     // print it in characters    // create a buffer to hold JSON data    buf := new(bytes.Buffer)    // create JSON encoder for `buf`    bufEncoder := json.NewEncoder(buf)    bufEncoder.Encode(john)    // print contents of the `buf`    fmt.Println(buf) // calls `buf.String()` method}bufEncoder.Encode(john)正在將 struct type( john) 編組為io.Writertype( buf)何時使用json.Marshal()vs Encoder.Encode()?因為buf兩者johnJSON都是[]byte類型type Buffer struct {    buf      []byte // contents are the bytes buf[off : len(buf)]    off      int    // read at &buf[off], write at &buf[len(buf)]    lastRead readOp // last read operation, so that Unread* can work correctly.}
查看完整描述

2 回答

?
富國滬深

TA貢獻1790條經驗 獲得超9個贊

Marshal( ) 是( Unmarshal) 的包裝。它們主要是便利功能,為較低級別的編碼器/解碼器實現提供方便的接口。EncoderDecoder

如果您需要處理包含多個 JSON 文檔的 JSON 流,或者如果您需要處理 JSON 流而不將整個文檔解組為內存結構,請使用解碼器。如果您有Reader,則可以使用Decoder代替Unmarshal

同樣,如果您正在生成沒有內存結構的 JSON 流,或者正在將多個 JSON 文檔寫入一個流,請使用Encoder. 如果您有Writer,則可以使用編碼器,而無需先將其解組為字節數組,然后再寫入。


查看完整回答
反對 回復 2022-06-13
?
慕后森

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

有三個不同之處。

如果 Marshal 函數和 Encoder 類型之間的特征差異不能決定它們之間的選擇,那么使用最方便的那個。Marshal 函數和 Encoder 類型共享它們的大部分實現并且具有相似的性能。Marshal 函數不是 Encoder 的包裝器,正如另一個答案中所聲稱的那樣。


查看完整回答
反對 回復 2022-06-13
  • 2 回答
  • 0 關注
  • 289 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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