Hi Bèrto,
as you said, you cannot put a type directly into a map. However you can
use package reflect to get type reflection information, that you can
put into a map.
But in this case I would simple use a map of constructor functions that
have a common interface.
Like this
https://go.dev/play/p/j3lb5pbpafT
You still need to assert a type to get to the concrete result type.
Or maybe you can come up with a sufficiant interface.
Have fun
On 4/11/23 23:11, Bèrto ëd Sèra wrote:
> Good evening,
>
> I do know there's no way to use
> var rule = map[uint8]interface{
> 0: thisType,
> 1: thatType,
> 4: someOtherType,
> .....
> }
>
> type Message interface {
> ....
> Become(data []byte)
> ....
> }
>
> type thisType struct {
> data []byte
> }
> func (my *thisType) Become(data []byte) { ....}
> type thatType struct {
> data []byte
> }
> func (my *thatType) Become(data []byte) { ....}
>
> WHAT I'M TRYING TO DO IS: I receive a data packet via UDP, it has an Id
> byte, a payload and ends with a crc32.
> |id|....payload....|crc32
>
> Upon reception I need to encapsulate the payload into a struct, and
> choose the right type of struct depending on the value of the ID byte.
> Different kinds of payloads get managed by different types of structs,
> the interface ensure all needed structs implement a common API.
>
> I wonder if there's a way to do what I'm trying to do without using a
> switch. Anything as declarative as a map would make things a lot easier
> for anyone who isn't familiar with the code. However, I see no way to
> use a map for this.
>
> Thanks in advance
> Berto
>
> --
> 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
golang-nuts...@googlegroups.com
> <mailto:
golang-nuts...@googlegroups.com>.
> To view this discussion on the web visit
>
https://groups.google.com/d/msgid/golang-nuts/0633636c-a1b6-40e7-9d3e-a49e352727ecn%40googlegroups.com <
https://groups.google.com/d/msgid/golang-nuts/0633636c-a1b6-40e7-9d3e-a49e352727ecn%40googlegroups.com?utm_medium=email&utm_source=footer>.