Hi all,

Assume I have a tcp server with incoming tcp packets which can be decoded 
in differently depending on some headers in that packet.

Each message that comes in has a struct associated with it which can be 
created with the traditionale NewX..(buf []byte ...). After creating the 
object (or inside the constructor, doesn't matter) the Decode() function is 
called to interpret the bytes and assign all the fields of the struct.

This works fine. But is it possible to eliminate all the 200+ functions 
that do the same thing but use a generic function instead?

So instead of this:

func NewMessageA(buf []byte) *MessageAStruct {
  m := &MessageAStruct{
    Buf: buf,
  }
  m.Decode()
  return m
}

msg := NewMessageA(buf)

I would rather do something like this:

msg := NewMessage[A](buf)

and I would've wanted to do something like this in the generic function

func NewMessage[T](buf []byte) *T {
  // ... something?
  // call Decode()
  // return *T
}

I can do it by creating an interface called Decodable and then passing the 
the type and the "empty" object to the generic function but it feels clumsy 
and weird somehow and I probably wouldn't gain very much. E.g.

func NewMessage[T Decodable](t T, buf []byte) T {
  t.Decode(buf)
  return t
}

and I would call it like this

msg := NewMessage[*MessageA](&MessageA{}, buf)

The most likely answer is "You shouldn't do it like that", which would be a 
completely fine and acceptable answer, but *can* you achieve this?

Cheers

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/5dc5715c-aad9-431f-8ea0-9c89db46d873n%40googlegroups.com.

Reply via email to