编译器不知道提供的特征方法

Compiler Unaware of Provided Methods of Trait

我正在以一种非常“hello world”的方式使用 prost crate,其中包含一个基本的 ProtoBuf 文件:

foo.proto

syntax = "proto3";
package foo;

message Foo {
    string mystring = 1;
}

我可以通过检查 ./target/PROJECT/build/PROJECT-{some hash}/out/foo.rs:

来验证 prost 在编译时生成的类型

foo.rs

#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Foo {
    #[prost(string, tag="1")]
    pub mystring: ::prost::alloc::string::String,
}

看到 prost::Message 特征得到派生了吗? Its docs 声称我有大量函数可以用于此特性,但只有两个必需的函数 encoded_len()clear() 可以无误地调用。任何提供的(具有默认实现的)都会导致 cannot find function in this scope 错误。

main.rs

use prost::Message;

pub mod foo {
    include!(concat!(env!("OUT_DIR"), "/foo.rs"));
}

fn main() {
    let f = foo::Foo { mystring: "bar".to_string() };
    let v = encode_to_vec(&f);
}

cargo run

error[E0425]: cannot find function `encode_to_vec` in this scope
   |
   |     let v = encode_to_vec(&f);
   |             ^^^^^^^^^^^^^ not found in this scope

而且,令人担忧的是,这个警告暗示它甚至没有查看它需要的特征:

warning: unused import: prost::Message

(编辑)供参考:

Cargo.toml

[package]
name = "testing"
version = "0.1.0"
edition = "2018"

[dependencies]
prost = { version = "0.7.0", features = ["std"] }

[build-dependencies]
prost-build = "0.7.0"

encode_to_vec 不是免费函数。您需要将其称为

之一
  • f.encode_to_vec()
  • foo::Foo::encode_to_vec(&f)
  • Message::encode_to_vec(&f)
  • <foo::Foo as Message>::encode_to_vec(&f)

第一种方法是最正常的,但当您对正在发生的事情感到困惑时,其他方法可能会产生有用的错误消息。


[编辑:]好吧,encode_to_vec 是在 prost 0.8.0, so with 0.7.0 中添加的,它将无法使用。