Golang Gob Type of next Variable

516 Views Asked by At

When using golang -> encoding/gob, I want to determine the type of the next variable I am going to get. One way of doing it, would be to alternate between an enum and the unknown variables, with the enum telling me what the next variable will be.

However, the gob-stream already knows the type of the next variable. (Or at least it's name, which would be good enough for me.) As can be seen in this example:

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)
}

It sees, that the next thing it gets has to be a struct with name vector and throws me an error. Is there a way to query the next type beforehead. (Again, without me explicitly sending it, in effect generating unnecessary overhead)

0

There are 0 best solutions below