1

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?

Jmb
  • 18,893
  • 2
  • 28
  • 55
Sanka Darshana
  • 1,391
  • 1
  • 23
  • 41

1 Answers1

1

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)
kmdreko
  • 42,554
  • 6
  • 57
  • 106