0Pricing
Learn Rust Coding · Ders

tonic-build ile Kod Oluşturma

proto'yu Rust koduna derleyin.

tonic-build ile Kod Oluşturma, CoddyKit'te ücretsiz bir Learn Rust Coding dersidir. Bu, 4 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Learn Rust Coding öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Learn Rust Coding kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

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-compiler

File 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.

Sıkça Sorulan Sorular

“tonic-build ile Kod Oluşturma” dersi ücretsiz mi?

Evet — “tonic-build ile Kod Oluşturma” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Learn Rust Coding kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Learn Rust Coding kursu toplamda 4 dersten oluşur.

“tonic-build ile Kod Oluşturma” dersinde ne öğreneceğim?

proto'yu Rust koduna derleyin. Learn Rust Coding ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Learn Rust Coding öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Learn Rust Coding, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 2. dersidir.

“tonic-build ile Kod Oluşturma” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Learn Rust Coding dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Learn Rust Coding dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Protobuf ve Hizmet Tanımları
  2. tonic-build ile Kod Oluşturma
  3. gRPC Sunucusu Uygulama
  4. gRPC İstemcisinden Çağrı Yapma
← Learn Rust Coding Sayfasına Dön