【问题标题】:Prost - the `encode` method cannot be invoked on a trait objectProst - 不能在 trait 对象上调用`encode` 方法
【发布时间】:2021-07-01 03:13:13
【问题描述】:

我正在尝试编写一个通用函数来使用以下代码对 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

如何解决这个问题?

【问题讨论】:

    标签: rust prost


    【解决方案1】:

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

    您可以改为将write_message 设为通用:

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

    【讨论】:

    • 谢谢。按预期工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多