Rust Traits: Defining Shared Behavior
Rust traits are like contracts that guarantee a type has certain methods, similar to interfaces. This lets you write functions that operate on any type with that behavior, like a summarize method for both articles and posts.
Why it exists
How do you write a single function that can operate on different types of data, like a news article and a social media post? Without a common blueprint, you'd need separate functions. Traits solve this by defining a shared set of behaviors that different types can promise to uphold, enabling code reuse and abstraction.
The mental model
A trait is a contract or an interface. It's a list of methods that a type must implement to be considered part of a group. If a NewsArticle struct and a SocialPost struct both implement the Summarizable trait, you know for a fact that you can call .summarize() on either one, even though the underlying data and logic are completely different.
How it works
You define a trait using the trait keyword, followed by the method signatures it requires. For example: pub trait Summary { fn summarize(&self) -> String; }. Notice there's no method body, just a signature ending in a semicolon. Then, for each type that needs this behavior, you provide a concrete implementation using an impl block: impl Summary for NewsArticle { ... }. The compiler enforces this contract, ensuring any type that claims to have the Summary trait actually provides a valid summarize method.
When to use it
Use traits to define behavior that can be shared across disparate types. This is the foundation of polymorphism in Rust. It's essential for writing generic functions that can accept any type that fulfills a certain contract (e.g., fn notify<T: Summary>(item: &T)). It allows libraries to define extension points for users to implement on their own types.
When not to use it
Don't use a trait for methods that are specific to a single, concrete type; a standard impl MyStruct block is for that. Traits are for abstract, shared behavior. Also, be aware of the 'orphan rule': you can't implement an external trait for an external type in your crate, as it would be unclear which implementation to use if multiple crates did this.
One canonical example
Define a Summary trait with a summarize method. Create two structs, NewsArticle and SocialPost. Implement Summary for both. The NewsArticle implementation might return headline, by author. The SocialPost implementation might return username: content. Now you can create a function print_summary(item: &impl Summary) that accepts an instance of either struct and successfully calls .summarize() on it, abstracting away the concrete type.
Interview question
What is the primary benefit of defining a Rust trait, such as Summary with a summarize method, and implementing it for multiple distinct types?
- a.It enforces that all implementing types must have the exact same internal data structure to support the summarize method.
- b.It allows writing generic functions that can operate on any type that fulfills the Summary contract, promoting code reuse.Correct
- c.It enables types to inherit data fields and state directly from the trait definition, similar to class inheritance.
- d.It automatically provides a default implementation for the summarize method if one is not explicitly defined by the implementing type.
Why? this is the answer
The card states traits enable "writing generic functions that can accept any type that fulfills a certain contract," which directly leads to code reuse and abstraction. Option D is a tempting distractor because traits can have default implementations, but the primary benefit isn't the automatic provision of a default, but rather the ability to treat different types uniformly based on their shared behavior.
Just read this? Test yourself on what you have been reading.
Read the original → doc.rust-lang.org
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on rust — each one lists the topics its interview covers.
See open roles