Prost - 无法在特征对象上调用 `encode` 方法

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

我正在尝试编写一个通用函数来使用以下代码对 prost 消息进行编码和解码。

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())
}

我收到以下错误。

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

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

如何解决这个问题?

函数 encode 不能用于特征对象,因为它使用泛型。

您可以改为 write_message 泛型:

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