tonic-build로 코드 생성하기
proto를 Rust 코드로 컴파일해 보세요.
tonic-build로 코드 생성하기은(는) CoddyKit의 무료 Learn Rust Coding 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Learn Rust Coding 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What tonic-build Does
tonic-build runs at compile time and turns your .proto files into Rust source. It wraps prost-build for messages and adds the gRPC service traits and clients on top.
It runs from a Cargo build script (build.rs), so generation happens automatically before your crate compiles.
Cargo Dependencies
You need runtime crates and a build-time crate. tonic and prost are normal dependencies; tonic-build goes under [build-dependencies].
tonic relies on tokio as its async runtime, so include it too.
[dependencies]
tonic = "0.12"
prost = "0.13"
tokio = { version = "1", features = ["full"] }
[build-dependencies]
tonic-build = "0.12"A Minimal build.rs
Create build.rs at the crate root. Call tonic_build::compile_protos with the path to your proto file.
This compiles both client and server code by default and writes it to the Cargo OUT_DIR.
fn main() -> Result<(), Box<dyn std::error::Error>> {
tonic_build::compile_protos("proto/greeter.proto")?;
Ok(())
}Configuring the Builder
For more control use tonic_build::configure(). You can disable client or server generation, set output paths, or add type attributes.
Here we generate the server but skip the client, useful for a pure backend crate.
tonic_build::configure()
.build_client(false)
.build_server(true)
.compile_protos(&["proto/greeter.proto"], &["proto"])?;Include Paths
The second argument to compile_protos is the list of include directories. Imports inside your proto, like google/protobuf/empty.proto, are resolved against these roots.
Always include the directory that contains your proto files so cross-file imports resolve.
tonic_build::configure()
.compile_protos(
&["proto/greeter.proto", "proto/health.proto"],
&["proto"],
)?;Where the Code Lands
Generated files are written to the directory in the OUT_DIR environment variable, named after the proto package, for example greeter.v1.rs.
You bring it into your crate with the include_proto! macro inside a module.
pub mod greeter {
pub mod v1 {
tonic::include_proto!("greeter.v1");
}
}What Gets Generated
For each service tonic produces a server module with a trait (for example greeter_server::Greeter) and a GreeterServer wrapper, plus a client struct GreeterClient.
Each message becomes a Rust struct deriving Clone, PartialEq, and prost's Message.
// generated (sketch):
// pub mod greeter_server { pub trait Greeter { /* methods */ } }
// pub mod greeter_client { pub struct GreeterClient<T> { /* ... */ } }Adding Derives with type_attribute
You often want extra derives on generated structs, such as serde::Serialize. Use type_attribute to inject attributes onto specific types or all of them with ..
This lets generated messages flow into JSON APIs or test fixtures.
tonic_build::configure()
.type_attribute(".", "#[derive(serde::Serialize)]")
.compile_protos(&["proto/greeter.proto"], &["proto"])?;Triggering Rebuilds
Cargo reruns build.rs only when it thinks inputs changed. Emit cargo:rerun-if-changed lines so edits to proto files force regeneration.
Without this, a changed proto may not regenerate until you touch a Rust file.
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("cargo:rerun-if-changed=proto/greeter.proto");
tonic_build::compile_protos("proto/greeter.proto")?;
Ok(())
}protoc Requirement
Historically tonic-build shelled out to the protoc compiler, which had to be installed. Modern versions can use the pure-Rust protox parser to avoid that dependency.
If you see a missing-protoc error, install protoc or enable a vendored compiler feature.
// In CI you may install protoc, e.g.:
// apt-get install -y protobuf-compilerFile Descriptor Sets
For reflection or advanced tooling, ask tonic-build to emit a file descriptor set with file_descriptor_set_path.
The resulting bytes can feed tonic-reflection, letting tools like grpcurl discover your services at runtime.
tonic_build::configure()
.file_descriptor_set_path(
std::env::var("OUT_DIR").unwrap() + "/greeter.bin")
.compile_protos(&["proto/greeter.proto"], &["proto"])?;Quick Check
Where does generated tonic code go and how is it loaded?
Recap
You set up dependencies, wrote a build.rs, configured client/server generation and include paths, loaded code via include_proto!, added derives, handled rebuild triggers, and learned about protoc and descriptor sets.
Next you will implement the server trait that tonic generated.
자주 묻는 질문
“tonic-build로 코드 생성하기” 강의는 무료인가요?
네 — “tonic-build로 코드 생성하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Learn Rust Coding 강의 전체를 잠금 해제할 수 있습니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.
“tonic-build로 코드 생성하기”에서 뭘 배우나요?
proto를 Rust 코드로 컴파일해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Learn Rust Coding을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Learn Rust Coding을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Learn Rust Coding은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“tonic-build로 코드 생성하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Learn Rust Coding 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Learn Rust Coding 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Protobuf와 서비스 정의
- tonic-build로 코드 생성하기
- gRPC 서버 구현하기
- gRPC 클라이언트에서 호출하기