普通网友 2014-12-04 05:34
浏览 122
已采纳

如何编码/解码一个空字符串

I am using the GOB encoding for my project and i figured out (after a long fight) that empty strings are not encoded/decoded correctly. In my code i use a errormessage (string) to report any problems, this errormessage is most of the time empty. If i encode a empty string, it become nothing, and this gives me a problem with decoding. I don't want to alter the encoding/decoding because these parts are used the most. How can i tell Go how to encode/decode empty strings?

Example: Playground working code. Playground not working code.

  • 写回答

1条回答 默认 最新

  • drju37335 2014-12-04 07:25
    关注

    The problem isn't the encoding/gob module, but instead the custom MarshalBinary/UnmarshalBinary methods you've declared for Msg, which can't correctly round trip an empty string. There are two ways you could go here:

    1. Get rid of the MarshalBinary/UnmarshalBinary methods and rely on GOB's default encoding for structures. This change alone wont' be enough because the fields of the structure aren't exported. If you're happy to export the fields then this is the simplest option: https://play.golang.org/p/rwzxTtaIh2

    2. Use an encoding that can correctly round trip empty strings. One simple option would be to use GOB itself to encode the struct fields:

      func (m Msg) MarshalBinary() ([]byte, error) {
          var b bytes.Buffer
          enc := gob.NewEncoder(&b)
          if err := enc.Encode(m.x); err != nil {
              return nil, err
          }
          if err := enc.Encode(m.y); err != nil {
              return nil, err
          }
          if err := enc.Encode(m.z); err != nil {
              return nil, err
          }
          return b.Bytes(), nil
      }
      
      // UnmarshalBinary modifies the receiver so it must take a pointer receiver.
      func (m *Msg) UnmarshalBinary(data []byte) error {
          dec := gob.NewDecoder(bytes.NewBuffer(data))
          if err := dec.Decode(&m.x); err != nil {
              return err
          }
          if err := dec.Decode(&m.y); err != nil {
              return err
          }
          return dec.Decode(&m.z)
      }
      

      You can experiment with this example here: https://play.golang.org/p/oNXgt88FtK

    The first option is obviously easier, but the second might be useful if your real example is a little more complex. Be careful with custom encoders though: GOB includes a few features that are intended to detect incompatibilities (e.g. if you add a field to a struct and try to decode old data), which are missing from this custom encoding.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败