💻 Programming

Trait

Trait

Defines shared behavior in Rust. Similar to interfaces. Combined with generics.

📖 Detailed Explanation

A Trait is an abstraction mechanism that defines shared behavior that a type must have. It declares method signatures similar to an Interface, but the key difference is that it can include a default implementation. In other words, a Trait defines "what can be done" while also being able to provide a default way of "how to do it," so it achieves both the contract role of an Interface and the code reuse of an abstract class.

In Rust, the Trait is a core language feature. You implement a Trait for a type with the impl Trait for Type syntax, and combined with generics it provides powerful polymorphism. Well-known Rust Traits include Clone (duplication), Debug (debug output), Iterator (iteration), and Send/Sync (thread safety). In particular, the strength of Rust Traits is that, through Trait Bounds (trait + constraints), they guarantee type safety at compile time while achieving zero-cost abstraction.

Traits in PHP and Scala have slightly different meanings. A PHP Trait is a code reuse mechanism for sharing methods between classes, and is included in a class with the use keyword. It is a practical solution that overcomes the limits of single inheritance while avoiding the diamond problem of multiple inheritance. Scala's Trait is similar in that it uses a mixin approach, allowing you to add functionality to a class by combining multiple Traits.

Traits are widely used in object-oriented programming as an alternative to multiple inheritance. Traditional multiple inheritance causes the diamond problem (two parent classes having the same method) and complex inheritance hierarchy problems, and Traits solve these through horizontal code sharing. Modern languages (Rust, Scala, PHP, and Kotlin's interface default methods) have adopted the Trait concept to support flexible and safe code reuse.

💻 Code Example

// Rust - Trait 정의와 구현 예제

// Trait 정의: 직렬화 가능한 타입의 동작 정의
trait Serializable {
    // 필수 구현 메서드 (시그니처만)
    fn serialize(&self) -> String;

    // 기본 구현이 있는 메서드
    fn serialize_pretty(&self) -> String {
        format!("[\n  {}\n]", self.serialize())
    }
}

// Trait 정의: 요약 기능
trait Summary {
    fn summarize(&self) -> String;

    // 기본 구현: summarize()를 호출
    fn summarize_author(&self) -> String {
        String::from("(작성자 미상)")
    }
}

// 구조체 정의
struct Article {
    title: String,
    author: String,
    content: String,
}

struct Tweet {
    username: String,
    content: String,
    retweets: u32,
}

// Article에 Trait 구현
impl Summary for Article {
    fn summarize(&self) -> String {
        format!("{}, by {}", self.title, self.author)
    }

    fn summarize_author(&self) -> String {
        format!("@{}", self.author)
    }
}

impl Serializable for Article {
    fn serialize(&self) -> String {
        format!(
            r#"{{"title":"{}","author":"{}","content":"{}"}}"#,
            self.title, self.author, self.content
        )
    }
}

// Tweet에 Trait 구현
impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {} (RT: {})", self.username, self.content, self.retweets)
    }
    // summarize_author는 기본 구현 사용
}

// Trait Bound를 사용한 제네릭 함수
fn notify(item: &T) {
    println!("속보! {}", item.summarize());
}

// 여러 Trait를 요구하는 함수 (+ 문법)
fn process(item: &T) {
    println!("요약: {}", item.summarize());
    println!("JSON: {}", item.serialize());
}

// where 절을 사용한 더 깔끔한 Trait Bound
fn complex_process(t: &T, u: &U) -> String
where
    T: Summary + Serializable,
    U: Summary,
{
    format!("{} & {}", t.summarize(), u.summarize())
}

fn main() {
    let article = Article {
        title: String::from("Rust Trait 완전 정복"),
        author: String::from("김러스트"),
        content: String::from("Trait는 Rust의 핵심 기능입니다..."),
    };

    let tweet = Tweet {
        username: String::from("rustacean"),
        content: String::from("Rust 최고!"),
        retweets: 42,
    };

    // Trait 메서드 호출
    println!("{}", article.summarize());        // "Rust Trait 완전 정복, by 김러스트"
    println!("{}", article.summarize_author()); // "@김러스트"
    println!("{}", tweet.summarize_author());   // "(작성자 미상)" - 기본 구현

    // 제네릭 함수 호출
    notify(&article);   // "속보! Rust Trait 완전 정복, by 김러스트"
    notify(&tweet);     // "속보! rustacean: Rust 최고! (RT: 42)"

    // 여러 Trait 요구하는 함수
    process(&article);  // Article은 Summary + Serializable 둘 다 구현
    // process(&tweet); // 컴파일 에러! Tweet은 Serializable 미구현
}

🗣️ Say It Like This in Practice

💬 In a Technical Interview (Trait vs Interface)
"The key difference between a Trait and an Interface is 'whether a default implementation is included.' An Interface is a pure contract that defines only 'what must be done,' but a Trait can also provide a default implementation of 'how to do it.' In Rust, like the Iterator trait, implementing just next() gives you dozens of default methods such as map, filter, and collect for free, enabling powerful code reuse."
💬 In a Design Meeting (Code Reuse)
"All models in this project need audit logging and soft delete functionality, but solving it with inheritance would make the hierarchy complex. If we separate them into Auditable and SoftDeletable Traits and add them with use only to the models that need them, it's much more flexible. This pattern is used a lot in PHP, and Laravel Eloquent's HasFactory and SoftDeletes are representative examples."
💬 In a code review
"In this Rust function, you used dyn Summary instead of impl Summary — is this a situation that requires dynamic dispatch? If it returns only a single type, impl Trait is advantageous for performance. You should use dyn only when you need to wrap multiple types in a Box and return them. A Trait Object has vtable overhead."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Attempting to Violate Rust's Orphan Rule

You cannot implement an external crate's Trait for an external crate's type. For example, you cannot implement Display for Vec. The solution is to wrap it with the newtype pattern (struct MyVec(Vec<T>)) or to define your own Trait.

❌
Ignoring PHP Trait Method Conflicts

If you use two Traits that have methods with the same name, a Fatal Error occurs. You must specify precedence with insteadof or create an alias with as. Do not ignore IDE warnings.

❌
Over-Reliance on State (Fields) in Traits

In PHP Traits you can define properties, but abusing this makes a class's internal state opaque. Focus Traits on sharing behavior (methods) and keep state to a minimum. If a lot of state is needed, consider the composition pattern.

✅
Designing Small, Single-Responsibility Traits

When a single Trait has too many methods, the implementation burden grows. Just as the Rust standard library separates Clone, Copy, and Debug, splitting related functionality into small Traits lets you implement only what you need.

🔗 Related Terms

📚 Learn More