gpt4 book ai didi

go - 反序列化未知的 Go 的 gob blob

转载 作者:IT王子 更新时间:2023-10-29 01:43:59 35 4
gpt4 key购买 nike

我有未知类型的采空区。有没有办法打印出来在里面查看?

可能有 gob.Debug 但我不可用 https://golang.org/src/encoding/gob/debug.go

谷歌搜索建议使用 DecodeValue 但它需要初始化 reflect.Value如果我得到未知的 gob blob,那么我无法传递未知类型的初始化值

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

package main

import (
"bytes"
"encoding/gob"
"fmt"
"reflect"
)


func encode1() []byte {

x := "123"

buf := &bytes.Buffer{}
enc := gob.NewEncoder(buf)
err := enc.Encode(x)
if err != nil {
panic(err)
}
return buf.Bytes()

}

func decode1(b1 []byte) {
var x string
dec := gob.NewDecoder(bytes.NewBuffer(b1))
err := dec.Decode(&x)
if err != nil {
panic(err)
}
fmt.Printf("%#v\n", x)
}

func decode2(b1 []byte) {
// var x reflect.Value
x := reflect.New(reflect.TypeOf(""))
dec := gob.NewDecoder(bytes.NewBuffer(b1))
err := dec.DecodeValue(x)
if err != nil {
panic(err)
}
fmt.Printf("%#v\n", x)
fmt.Printf("%#v\n", reflect.Indirect(x))
}

func main() {
b1 := encode1()
decode1(b1)
decode2(b1)
}

最佳答案

你需要Register编码解码前的类型

Register records a type, identified by a value for that type, under its internal type name. That name will identify the concrete type of a value sent or received as an interface variable. Only types that will be transferred as implementations of interface values need to be registered. Expecting to be used only during initialization, it panics if the mapping between types and names is not a bijection.

关于go - 反序列化未知的 Go 的 gob blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53467734/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com