简体   繁体   English

如何在 rust 中使用 prost 生成代码?

[英]How to generate codes using prost in rust?

I don't know how to generate codes using prost_build我不知道如何使用prost_build生成代码

I have read the documents, but they don't give a detailed command of generating code.我已经阅读了文档,但它们没有给出生成代码的详细命令。 I type cargo build but no codes are generated.我输入cargo build但没有生成代码。

my build.rs我的build.rs

extern crate prost_build;
fn main() {
    prost_build::compile_protos(&["src/items.proto"],
                                &["src/"]).unwrap();
}

my Cargo.toml我的Cargo.toml

[package]
name = "snazzy"
version = "0.1.0"
authors = ["xxx <xxx@xxx.com>"]
edition = "2018"
build = "build.rs"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
bytes = "0.4"
prost = "0.5"

[build-dependencies]
prost-build = { version = "0.4"  }

my items.proto我的items.proto

syntax = "proto3";

package snazzy.items;

message Shirt {
    enum Size {
        SMALL = 0;
        MEDIUM = 1;
        LARGE = 2;
    }
    string color = 1;
    Size size = 2;
}

my file tree:我的文件树:

.
├── build.rs
├── Cargo.lock
├── Cargo.toml
└── src
    ├── items.proto
    └── main.rs

No build error but I can't see where the generated codes are.没有构建错误,但我看不到生成的代码在哪里。 Any help will be appreciated!任何帮助将不胜感激!

You're right, this isn't very well explained in the docs, and this is because of the way build scripts work.你是对的,这在文档中没有得到很好的解释,这是因为构建脚本的工作方式。 Well, partly.好吧,部分。

Your protobuf implementations are under target/{yourArch}/build/{yourCrateName}-{hash}/out .您的 protobuf 实现位于target/{yourArch}/build/{yourCrateName}-{hash}/out

This would be extremely hard to get to if it wasn't for environment variables.如果不是环境变量,这将是非常难以实现的。 The important part of the documentation is the following snippet of code highlights the inclusion:文档的重要部分是以下代码片段突出显示了包含:

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

This includes the file available at OUT_DIR (the directory specified above, filled in automatically during compilation) and the name of the protobuf implementation (your package name in the protobuf file), and makes all its content structs available under crate::items .这包括OUT_DIR中可用的文件(上面指定的目录,在编译期间自动填写)和 protobuf 实现的名称(您在 protobuf 文件中的 package 名称),并使其所有内容结构在crate::items下可用。

It makes sense for the files to reside in the build directory, as they are a build artefact.将文件驻留在构建目录中是有意义的,因为它们是构建工件。 Code generation in the src folder of your crate would lead to chaos, both when it comes to version control and project sanity (you'd have a duplication of information, and the protobuf implementation, provided that it is sane, isn't that important to you. The functional blueprint is, however).在你的 crate 的src文件夹中生成代码会导致混乱,无论是在版本控制和项目完整性方面(你会有重复的信息,而且 protobuf 实现,只要它是理智的,不是那么重要给你。但是,功能蓝图是)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM