第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

gob 嘗試解碼 nil 值導致 EOF 錯誤

gob 嘗試解碼 nil 值導致 EOF 錯誤

Go
慕的地6264312 2022-01-17 20:05:49
我需要使用gob對一些數(shù)據(jù)進行編碼,但是,我發(fā)現(xiàn)無法正確處理“type nil”(轉到 1.6.2)https://play.golang.org/p/faypK8uobFpackage mainimport (    "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
查看完整描述

1 回答

?
尚方寶劍之說

TA貢獻1788條經(jīng)驗 獲得超4個贊

你正在吞下一個error返回的Encoder.Encode():


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緩沖區(qū))寫入任何內容,因此嘗試從中讀?。ń獯a)任何內容都會導致 EOF。


但是為什么你不能編碼一個interface{}持有nil指針的值呢?引用包文檔encoding/gob:


指針不被傳輸,但它們指向的東西被傳輸;也就是說,這些值是扁平的。


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


這是 github 上的一個相關問題:encoding/gob: panic on encoding nil pointer #3704


拉斯:


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


羅布·派克:


正確的。只有具體值本身是可傳輸?shù)?,才能傳輸接口值。至少現(xiàn)在,這相當于說不能發(fā)送持有類型化 nil 指針的接口。


查看完整回答
反對 回復 2022-01-17
  • 1 回答
  • 0 關注
  • 245 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號