首頁 >後端開發 >Golang >為什麼我在 Go 中收到「gob: type not Registered for interface: map[string]interface {}」錯誤?

為什麼我在 Go 中收到「gob: type not Registered for interface: map[string]interface {}」錯誤?

Patricia Arquette
Patricia Arquette原創
2024-11-11 09:29:03436瀏覽

Why do I get the

錯誤:「gob:類型未註冊介面:map[string]interface {}」

在Go將值編碼和解碼為二進位表示法。但是,當嘗試使用 gob 編碼 map[string]interface{} 值時,您可能會遇到錯誤:

gob: type not registered for interface: map[string]interface {}

此錯誤表示 gob 套件不知道類型 map[string]介面{}。要解決此問題,您必須使用 gob.Register 函數明確註冊類型。

gob.Register(map[string]interface{}{})

透過註冊類型,您將通知gob 套件它應該識別並處理map[string]interface{

這是您提供的程式碼的修改版本,其中包括必要的註冊:

package main

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

func CloneObject(a, b interface{}) []byte {
    buff := new(bytes.Buffer)
    enc := gob.NewEncoder(buff)
    dec := gob.NewDecoder(buff)
    // Register the map[string]interface{} type for encoding
    gob.Register(map[string]interface{}{})
    err := enc.Encode(a)
    if err != nil {
        log.Panic("e1: ", err)
    }
    b1 := buff.Bytes()
    err = dec.Decode(b)
    if err != nil {
        log.Panic("e2: ", err)
    }
    return b1
}

func main() {
    var a interface{}
    a = map[string]interface{}{"X": 1}
    b2, err := json.Marshal(&a)
    fmt.Println(string(b2), err)

    var b interface{}
    b1 := CloneObject(&a, &b)
    fmt.Println(string(b1))
}

註冊類型後,您可以成功編碼和解碼使用gob.

映射[字串]介面{}值

以上是為什麼我在 Go 中收到「gob: type not Registered for interface: map[string]interface {}」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn