트레이트 제약
트레이트로 제네릭의 범위를 제한해 보세요.
트레이트 제약은(는) CoddyKit의 무료 Learn Rust Coding 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Learn Rust Coding 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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.
자주 묻는 질문
“트레이트 제약” 강의는 무료인가요?
네 — “트레이트 제약” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Learn Rust Coding 강의 전체를 잠금 해제할 수 있습니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.
“트레이트 제약”에서 뭘 배우나요?
트레이트로 제네릭의 범위를 제한해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Learn Rust Coding을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Learn Rust Coding을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Learn Rust Coding은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“트레이트 제약” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Learn Rust Coding 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Learn Rust Coding 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.