Go -- 中結構體與字節數組能相互轉化


編碼時如下,假設默認你的結構體為data

func Encode(data interface{}) ([]byte, error) {  
        buf := bytes.NewBuffer(nil)  
        enc := gob.NewEncoder(buf)  
        err := enc.Encode(data)  
        if err != nil {  
            return nil, err  
        }  
        return buf.Bytes(), nil  
    } 

解碼時如下,data為需要解碼的字節數組,to為相應的接收結構體,記住to的結構體結構應與被編碼的data相一致(這就是gob相對於json的缺陷,解碼需要預先知道被解碼內容的結構),解碼后內容保存在to里面,直接使用to即可

 

func Decode(data []byte, to interface{}) error {  
    buf := bytes.NewBuffer(data)  
    dec := gob.NewDecoder(buf)  
    return dec.Decode(to)  
} 

 

使用的時候:

b, err := Encode(data)  
    if err != nil {  
       //錯誤處理 
    }  
    if err := Decode(b, &to); err != nil {  
        //錯誤處理
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM