Trait
Trait
Rust's way of defining shared behavior. Similar to interfaces. Combined with generics to implement polymorphism.
Trait
Rust's way of defining shared behavior. Similar to interfaces. Combined with generics to implement polymorphism.
A trait is a way to define shared behavior in Rust. It is similar to interfaces in other languages, but it is more flexible in that it can provide default implementations and can be implemented for existing types. Traits are at the core of Rust's polymorphism and generics system.
A trait defines a set of method signatures. When a type implements (impl) a trait, it must provide those methods. If a trait has a default implementation, the implementing type does not have to override it. This ensures code reuse and a consistent interface.
Trait bounds let you place constraints on generic types. fn print<T: Display>(item: T) accepts only types that implement the Display trait. A where clause can also express complex bounds cleanly.
Clone, Copy, Debug, Default, PartialEq and others in the Rust standard library are commonly used traits. The #[derive] macro enables automatic implementation, reducing boilerplate code. Using dyn Trait also enables runtime polymorphism (dynamic dispatch).
// Rust 트레이트 예제
// 1. 트레이트 정의
trait Drawable {
fn draw(&self);
// 기본 구현
fn description(&self) -> String {
String::from("A drawable object")
}
}
// 2. 트레이트 구현
struct Circle {
radius: f64,
}
impl Drawable for Circle {
fn draw(&self) {
println!("Drawing circle with radius {}", self.radius);
}
}
struct Rectangle {
width: f64,
height: f64,
}
impl Drawable for Rectangle {
fn draw(&self) {
println!("Drawing rectangle {}x{}", self.width, self.height);
}
fn description(&self) -> String {
format!("Rectangle {}x{}", self.width, self.height)
}
}
// 3. 트레이트 바운드
fn draw_all(items: &[T]) {
for item in items {
item.draw();
}
}
// 4. where 절
fn compare_and_draw(a: T, b: U)
where
T: Drawable + Clone,
U: Drawable + Default,
{
a.draw();
b.draw();
}
// 5. 동적 디스패치
fn draw_dynamic(item: &dyn Drawable) {
item.draw();
}
// 6. derive 매크로
#[derive(Debug, Clone, PartialEq)]
struct Point {
x: i32,
y: i32,
}
Senior: We need to support multiple storage backends. Let's abstract it with a trait.
Junior: Should I define read and write methods on a Storage trait?
Senior: Yes, and if you use the async_trait crate, you can also define async methods in the trait. Each backend (S3, local, Redis) just needs to implement this trait.
Interviewer: What is the difference between a Rust trait and a Java interface?
Candidate: A trait can provide a default implementation, and a trait can be implemented externally for existing types. Also, the way trait bounds constrain generics is different. Java's default methods are similar, but Rust is more flexible.
Interviewer: What is the difference between static dispatch and dynamic dispatch?
Candidate: With static dispatch, the function to be called is determined at compile time, which enables inline optimization. Dynamic dispatch (dyn Trait) is determined at runtime through a vtable, which is flexible but has slight overhead.
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Reviewer: This generic function has too many trait bounds. It looks like it needs refactoring.
Author: Because it needs a lot of functionality.
Reviewer: It would be better to create a supertrait that combines several traits, or to split the function. If the where clause exceeds 5 lines, reconsider the design.