簡體   English   中英

料滴嘗試解碼nil值會導致EOF錯誤

[英]gob attempting to decode nil value results in EOF error

我需要使用gob編碼一些數據,但是,我發現無法正確處理“類型nil”(轉到1.6.2)

https://play.golang.org/p/faypK8uobF

package main

import (
    "bytes"
    "encoding/gob"
    "log"
)

type T struct {
    A int
}

func init() {
    gob.Register(map[string]interface{}{})
    gob.Register(new(T))
}
func main() {
    bys := bytes.NewBuffer(nil)
    gob.NewEncoder(bys).Encode(map[string]interface{}{
        "v": (*T)(nil),
    })
    out := map[string]interface{}{}
    if err := gob.NewDecoder(bys).Decode(&out); err != nil {
        log.Panic(err)
    }
    return
}

輸出:

panic: EOF

您正在吞下Encoder.Encode()返回的error

err := gob.NewEncoder(bys).Encode(map[string]interface{}{
    "v": (*T)(nil),
})
if err != nil {
    fmt.Println(err)
}

輸出:

gob: gob: cannot encode nil pointer of type *main.T inside interface

這是由未導出的方法Encoder.encodeInterface()生成的。 引用來自encode.go未導出方法Encoder.encodeInterface()

// Gobs can encode nil interface values but not typed interface
// values holding nil pointers, since nil pointers point to no value.
elem := iv.Elem()
if elem.Kind() == reflect.Ptr && elem.IsNil() {
    errorf("gob: cannot encode nil pointer of type %s inside interface", iv.Elem().Type())
}

因此,您的Encoder.Encode()失敗,它不向其輸出(即bys緩沖區)寫入任何內容,因此嘗試從中讀取(解碼)任何內容都會導致EOF。

但是,為什么不能編碼包含nil指針的interface{}值呢? 引用來自encoding/gob的軟件包文檔:

指針不被傳輸,但是指針所指向的事物被傳輸。 即,將值展平。

您的interface{}包含一個指針類型的值,但該指針為nil ,它指向無內容,不能被展平。


這是github上的一個相關問題: encoding / gob:編碼nil指針時出現恐慌#3704

拉斯:

gob不知道指針是什么:一切都變平了。 將nil指針放在interface {}值中會創建一個gob無法發送(它不能表示“ nil指針”)的非零值(這不是nil接口)。

羅伯·派克:

正確。 僅當具體值本身可傳輸時,才能傳輸接口值。 至少就目前而言,這相當於說無法發送包含類型為nil指針的接口。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM