duanjie5570 2014-09-27 01:52
浏览 49
已采纳

为什么json.Marshal和json.Unmarshal具有不同的签名

func Marshal(v interface{}) ([]byte, error)
func Unmarshal(data []byte, v interface{}) error

notice that Marshal accept an interface and return a []byte as output, while Unmarshal accept an []byte and write output directly to the input parameter data

what make the difference in design

an associate question:

I think use input parameter could save in-memory copy once(function return need a copy), every assignment in golang is a copy op, so it looks like Unmarshal can save a copy, but Marshal not.

so I'm confused...

  • 写回答

2条回答 默认 最新

  • dpwle46882 2014-09-27 04:42
    关注

    The potential functions in symmetric pairs are:

    func Marshal(v interface{}) ([]byte, error)         // 1
    func Unmarshal(data []byte) (interface{}, error)    // 2
    
    func Marshal(v interface{}, data *[]byte) error     // 3
    func Unmarshal(data []byte, v interface{}) error    // 4
    

    Functions #3 and #4 might not look symmetric because the data argument to #3 is a pointer type and the v argument to #4 is not declared to be a pointer type. They are in fact symmetric because the actual value passed to the v argument of #4 must be a pointer. The function returns an error if it is not a pointer.

    Function #2 is not viable because the function does not have access to the application's result type. The function cannot unmarshal the JSON to a type if the type is not known to the function. Further, the application will need to type assert the result to use it. The standard library avoids type assertions when possible.

    Function #3 is not idiomatic. Pointers to slices are rarely used in Go. I don't recall the use of any in the standard library, but I am sure someone will leave a comment here if there is a one.

    We are left with the unsymmetric pair of #1 and #4:

    func Marshal(v interface{}) ([]byte, error)         // 1
    func Unmarshal(data []byte, interface{}) error      // 4
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?