I've been trying to get this code to compile
pub trait Packet: PacketSerializer + ProtocolToID + Default {
fn serialize_with_id(&self, ver: &ProtocolVersion) -> Box<ByteBuf>;
fn deserialize_gen(buf: &mut ByteBuf) -> Box<Self>;
}
impl<T: PacketSerializer + ProtocolToID + PacketHandler + Default> Packet for T
{
fn serialize_with_id(&self, ver: &ProtocolVersion) -> Box<ByteBuf> {
let mut buf = Box::new(ByteBuf::new());
buf.write_var_int(self.resolve_id(ver));
self.serialize(&mut buf, &ver);
buf
}
fn deserialize_gen(buf: &mut ByteBuf) -> Box<T> {
let mut p: T = Default::default();
p.deserialize(buf);
Box::new(p)
}
}
pub fn invoke_packet_handler(id: i32, buf: &mut ByteBuf) -> Box<dyn Packet> {
Box::new(clientbound::SetCompression { threshold: 256 })
}
specifically invoke_packet_handler
is supposed to return a Box<dyn Packet>
According to the docs, this should work https://doc.rust-lang.org/rust-by-example/trait/dyn.html if you "statically" define the trait so the compiler can see it.
I get the following error at runtime
error[E0038]: the trait `Packet` cannot be made into an object
--> src/serialize/packet.rs:43:61
|
43 | pub fn invoke_packet_handler(id: i32, buf: &mut ByteBuf) -> Box<dyn Packet> {
| ^^^^^^^^^^^^^^^ `Packet` cannot be made into an object
I'm assuming this is because of the implementation for Packet
? It's generic on every type that implements PacketSerializer
, ProtocolToID
, PacketHandler
and Default
However,
pub fn invoke_packet_handler(id: i32, buf: &mut ByteBuf) -> Box<dyn PacketHandler> {
Box::new(clientbound::SetCompression { threshold: 256 })
}
does compile if I specify a single trait