0Pricing
Learn Rust Coding · Ders

Trait Sınırları

Jenerikleri trait'lerle kısıtlayın.

Trait Sınırları, CoddyKit'te ücretsiz bir Learn Rust Coding dersidir. Bu, 4 dersinin 3. 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 Trait Bounds Do

A trait bound restricts a generic type to those that implement a given trait. It tells the compiler what behavior the type guarantees.

This unlocks the trait's methods inside the generic code while keeping the function usable for many types.

Inline Bound Syntax

The simplest form places the bound right after the type parameter: T: Trait. Here T must implement Display so it can be printed.

Inside the function you may now call any method that Display provides.

use std::fmt::Display;

fn show<T: Display>(value: T) {
    println!("value = {}", value);
}

A Custom Trait

Bounds work with your own traits too. Define a trait with a method, then bound a generic function by it.

This Summary trait requires a summarize method returning a string.

trait Summary {
    fn summarize(&self) -> String;
}

Implementing and Bounding

Implement the trait for a type, then a bounded function can accept any implementor. The function calls the trait method without knowing the concrete type.

This full program prints a summary of an Article.

trait Summary { fn summarize(&self) -> String; }

struct Article { title: String }

impl Summary for Article {
    fn summarize(&self) -> String {
        format!("Article: {}", self.title)
    }
}

fn notify<T: Summary>(item: &T) {
    println!("{}", item.summarize());
}

fn main() {
    let a = Article { title: String::from("Rust") };
    notify(&a);
}

Combining Bounds With +

Require several traits at once by joining them with +. Here T must implement both Display and Clone.

The function can then print the value and also clone it.

use std::fmt::Display;

fn process<T: Display + Clone>(value: T) {
    let copy = value.clone();
    println!("{}", copy);
}

impl Trait in Arguments

The impl Trait syntax in an argument position is shorthand for a simple bound. item: &impl Summary means the same as a <T: Summary> parameter.

It is concise for single-argument cases but offers less control when you reuse the type.

trait Summary { fn summarize(&self) -> String; }

fn notify(item: &impl Summary) {
    println!("{}", item.summarize());
}

Returning impl Trait

You can also return impl Trait to hide a concrete type while promising it implements a trait. This is handy for closures and iterators.

The caller knows only that the result implements the named trait.

fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
    move |x| x + n
}

fn main() {
    let add5 = make_adder(5);
    println!("{}", add5(10));
}

Bounds Enable Operators

Operators map to traits: + needs Add, == needs PartialEq, comparisons need PartialOrd. Bounding by these lets generic code use the operators.

Here summing requires that T implement Add with itself.

use std::ops::Add;

fn sum<T: Add<Output = T>>(a: T, b: T) -> T {
    a + b
}

Default Trait Methods

Traits can provide default method bodies. Implementors may override them or rely on the default. Bounded generics use whichever is in effect.

This Summary has a default summarize that types can keep as-is.

trait Summary {
    fn summarize(&self) -> String {
        String::from("(no summary)")
    }
}

struct Note;
impl Summary for Note {}

Static vs Dynamic Dispatch

Trait bounds use static dispatch: the compiler picks the exact method at compile time via monomorphization. By contrast dyn Trait uses dynamic dispatch through a vtable.

Bounds are usually faster; dyn trades speed for smaller binaries and runtime flexibility.

Bounds on Generic Structs

Trait bounds are not limited to functions. You can require them when defining a struct so all instances satisfy the trait.

Here every Sortable<T> guarantees its items can be compared.

struct Sortable<T: PartialOrd> {
    items: Vec<T>,
}

Quick Check

Test your understanding of trait bounds.

Recap

Trait bounds constrain generic types so the compiler permits the trait's methods and operators. Combine traits with +, and use impl Trait as shorthand in arguments or returns.

Bounds give static dispatch with zero overhead, unlike dyn Trait dynamic dispatch.

Sıkça Sorulan Sorular

“Trait Sınırları” dersi ücretsiz mi?

Evet — “Trait Sınırları” 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.

“Trait Sınırları” dersinde ne öğreneceğim?

Jenerikleri trait'lerle kısıtlayın. 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 3. dersidir.

“Trait Sınırları” 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. Jenerik İşlevler
  2. Jenerik Struct'lar ve Enum'lar
  3. Trait Sınırları
  4. where İfadeleri ve Birden Çok Sınır
← Learn Rust Coding Sayfasına Dön