mercredi 27 septembre 2023

Create pointer with inited object from pointer type in generic struct

type TypedConnection[Receive, Send proto.Message] struct {
    raw_connection Connection
}
func MakeTypedConnection[Receive, Send proto.Message](raw_connection Connection) TypedConnection[Receive, Send] {
    return TypedConnection[Receive, Send]{
        raw_connection: raw_connection,
    }
}
func (this *TypedConnection[Receive, Send]) Receive() (message Receive, err error) {
    var data Data
    data, err = this.raw_connection.Receive()
    if err == nil {
        var bytes []byte
        bytes, err = data.Bytes()
        if err == nil {
            message = new(Receive)
            err = proto.Unmarshal(bytes, message)
        }
    }
    return message, err
}

Error is on line message = new(Receive), since Receive is pointer I can not create pointer to *Receive using new(Receive) Is there anyway to overcome pointer type to create initialized pointer?

Usage of TypedConnection

stream := transfer.MakeTypedStream[*set.Request, *set.Response](raw_stream)

I tried to replace generic constraints from proto.Message to any, but in this case I won't be able to do proto.Unmarshal(bytes, message)

I was thinking of reflection and trying call new through it, but if it will success I will need to do casts, what I find really stupid when you have generics

I expect to find answer with something like new(*Receive)





Aucun commentaire:

Enregistrer un commentaire