My first question would be, is the type encoded into the CBOR blob somehow?
Like by a tag?
If structs are encoded as maps, with no type information, then the input
doesn't have enough information to do what you want. How could the blob
(using JSON notation)
{"X": 1, "Y": 2}
know whether it should decode into
type Point struct { X, Y int}
or
type Chromosome {X, Y int}
?
You have to encode the type somehow. If you control the encoding process
and you're encoding a fixed set of types that you want to distinguish at
decode time,
you can do something like this:
type (
This ...
That ...
TheOther ...
Thing struct {
This *This
That *That
TheOther *TheOther
}
)
To encode a `This` named `t`, actually encode `Thing{This: &t}`. When you
decode that into a `Thing`, only the `This` field will be non-nil, so you
know you've got a `This`.
(Disclaimer: I know this technique works with the encoding/json package; I
can't guarantee it works with the cbor package you're using because I'm not
familiar with it,
but if it behaves like encoding/json, you should be OK.)
On Wednesday, July 8, 2020 at 3:44:36 PM UTC-4, David Stainton wrote:
>
>
> Greetings,
>
> Similar questions have been asked in the past and I've read those posts...
> and I believe I'm asking something different here.
>
> I'm using length prefixed CBOR over unix domain socket as my wire format.
> However the reader doesn't known which CBOR type it needs to decode.
> I'd like a mechanism similar to the golang switch type assertion where a
> known set of types are specified.
>
> Before you go and tell me to use the empty interface let me explain that
> certainly this works:
>
> // "github.com/fxamacker/cbor"
> var v interface{}
> err = cbor.Unmarshal(out, &v)
>
> It works for some definitions of "works". It doesn't tell me what type it
> is but it does allow me to access each struct field by name in the map of
> type: map[interface {}]interface {}
>
> The reason this is not good enough is that it doesn't concretely tell me
> the type!
> Of course I could go ahead and add a struct field called TypeName and set
> it's value to a string encoding the name. But that feels wrong and I'd feel
> bad after writing it.
>
> I've also tried to ask this question on a ticket here:
> https://github.com/fxamacker/cbor/issues/241
>
> Is the least incorrect solution to iteratively try cbor.Unmarshal with all
> the types in the known set of possible types until one of them works?
>
> Certainly this problem isn't specific to CBOR. Am I asking the question
> incorrectly here?
>
>
> Sincerely,
> David
>
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/019fb798-f282-451d-947c-79a7c1bc2b98o%40googlegroups.com.