zoukankan      html  css  js  c++  java
  • 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 {  
            //错误处理
        }
  • 相关阅读:
    3-1
    3-2
    习题二 8
    习题二 3
    习题二 5
    习题二 4
    习题二 6
    实验三-2未完成
    实验三
    心得
  • 原文地址:https://www.cnblogs.com/mafeng/p/7183252.html
Copyright © 2011-2022 走看看