php editor Youzi discussed a common question: Is there a way to constrain (general) type parameters? In PHP, we often need to impose type constraints on the parameters of functions or methods to ensure that the parameters passed in meet specific type requirements. However, there is currently no direct way to constrain generic type parameters, such as arrays or objects. However, we can implement constraints on common type parameters by writing more strict type checking logic to ensure the correctness and consistency of the parameters. In this article, we'll explore several ways to implement generic type parameter constraints, as well as their pros and cons.
I just started learning generics. So I'm trying to generalize a driver for a custom database that runs on some protobuf messages.
I would like to find a way to further constrain my generic type, but as a pointer, i.e. make sure (tell the compiler) that the constraint e implements another method.
First, I limited the entities that the database can handle.
type entity interface { pb.msga | pb.msgb | pb.msgc }
Then, a common interface describing the functionality of the database was written so that it could be used by different services handling their own raw messages:
type db[e entity] interface { get(...) (e, error) list(...) ([]e, error) ... }
So far so good. However, I also want to (de)serialize these entities when communicating with the database so that they can be sent over the network, cloned and merged. Something like this:
func encode[e entity](v *e) ([]byte, error) { return proto.marshal(v) }
However, the above code gives the following error:
cannot use val (variable of type *e) as type protoreflect.protomessage in argument to proto.marshal: *e does not implement protoreflect.protomessage (type *e is pointer to type parameter, not type parameter)
The problem is that proto.marshal
requires entities (*e) to implement the proto.message
interface, i.e. the protoreflect()
method, for all my entity types Both implement the method, but it is unconstrained and cannot be inferred by the compiler.
I also tried defining the entity as:
type Entity interface { *pb.MsgA | *pb.MsgB | *pb.MsgC proto.Message }
However, this doesn't feel right, besides the fact that I need to do some extra protreflect operations to instantiate the proto.messages referenced by the entity pointer.
You can do this:
func encode[m interface { *e; proto.message }, e entity](v m) ([]byte, error) { return proto.marshal(v) }
If you want a more concise syntax than the above, you can cancel the message constraint:
type Message[E Entity] interface { *E proto.Message } func Encode[M Message[E], E Entity](v M) ([]byte, error) { return proto.Marshal(v) }
https://www.php.cn/link/20ba66f905957b34253d9d7abde919f3
The above is the detailed content of Is there a way to constrain (generic) type parameters?. For more information, please follow other related articles on the PHP Chinese website!