普通网友 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 idea自动补全键位冲突
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 定制ai直播实时换脸软件
  • ¥100 栈回溯相关,模块加载后KiExceptionDispatch无法正常回溯了
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页