Encoding 下一个变量的Golang Gob类型
使用golang->encoding/gob时,我想确定下一个变量的类型。 一种方法是在枚举和未知变量之间交替,枚举告诉我下一个变量是什么 但是,gob流已经知道下一个变量的类型。 (或者至少是名字,对我来说就足够了。) 如本例所示:Encoding 下一个变量的Golang Gob类型,encoding,go,gob,Encoding,Go,Gob,使用golang->encoding/gob时,我想确定下一个变量的类型。 一种方法是在枚举和未知变量之间交替,枚举告诉我下一个变量是什么 但是,gob流已经知道下一个变量的类型。 (或者至少是名字,对我来说就足够了。) 如本例所示: package main import ( "bytes" "encoding/gob" "fmt" "log" ) type Vector struct { X, Y, Z int } func main() {
package main
import (
"bytes"
"encoding/gob"
"fmt"
"log"
)
type Vector struct {
X, Y, Z int
}
func main() {
var network bytes.Buffer // Stand-in for the network.
// Create an encoder and send a value.
enc := gob.NewEncoder(&network)
err := enc.Encode(Vector{3, 4, 5})
if err != nil {
log.Fatal("encode:", err)
}
// Create a decoder and receive a value.
dec := gob.NewDecoder(&network)
var v interface{}
err = dec.Decode(&v)
if err != nil {
// This will run, outputting:
// local interface type *interface {} can only be decoded from remote interface type; received concrete type Vector = struct { X int; Y int; Z int; }
log.Fatal("decode:", err)
}
fmt.Println(v)
}
它看到,它得到的下一个东西必须是一个名为vector的结构,并向我抛出一个错误。
是否有一种方法可以在head之前查询下一个类型。(同样,如果我不显式地发送它,实际上会产生不必要的开销)如果不做完全不安全的事情,例如使用
unsafe
包来调用解码器对象上的私有方法,答案是否定的-他们必须显式地添加对此的支持,因为当前的API不允许这样做。