rustprost

Prost - the `encode` method cannot be invoked on a trait object


I'mm trying to write a generic function to encode and decode prost messages with the below code.

pub fn write_message(&mut self, message: &mut dyn prost::Message) -> std::io::Result<usize> {
    let mut buf: Vec<u8> = Vec::new();
    buf.reserve(message.encoded_len());
    message.encode(&mut buf).unwrap();
    self.stream.write(&*buf);
    Ok(buf.len())
}

I'm getting the following error with this.

error: the `encode` method cannot be invoked on a trait object    
|         message.encode(&mut buf).unwrap();    
|                 ^^^^^^    | 

   | 50 |         Self: Sized,    |               ----- this has a
`Sized` requirement

How to fix this?


Solution

  • The function encode can't be used on trait objects since it uses generics.

    You can make write_message generic instead:

    fn write_message<M: prost::Message>(&mut self, message: &mut M)