Google News
logo
Rust - Interview Questions
What are traits in Rust?
In Rust, traits are a way to define shared behavior or capabilities that types can implement. Traits allow you to define a set of methods that can be implemented by different types, enabling code reuse and providing a form of interface-like functionality.

Here are the key points to understand about traits in Rust :

1. Trait Declaration : Traits are declared using the `trait` keyword followed by the trait name and a code block. Within the code block, you define the methods and associated types that the trait requires or provides.
trait Printable {
    fn print(&self);
}​

2. Method Requirements : Traits can specify methods that implementing types must provide. These method declarations don't contain implementations; they only define the method signatures.

3. Default Method Implementations : Traits can also provide default implementations for some or all of their methods. Types implementing the trait can choose to override these default implementations if desired.
trait Printable {
    fn print(&self) {
        println!("Default implementation");
    }
}​

4. Trait Implementation : Types can implement traits by providing the implementations for the required methods. This is done using the `impl TraitName for TypeName` syntax. Multiple traits can be implemented for a single type.
struct Person {
    name: String,
}

impl Printable for Person {
    fn print(&self) {
        println!("Name: {}", self.name);
    }
}​
5. Trait Bounds : Trait bounds allow you to constrain generic types to only accept types that implement certain traits. This enables generic code to utilize the behavior defined by a trait.
fn print_info<T: Printable>(item: T) {
    item.print();
}​

6. Associated Types : Traits can have associated types, which allow you to define a type that is associated with the trait. Associated types are specified using the `type` keyword within the trait declaration and can be used as part of the trait's method signatures.
trait Container {
    type Item;
    
    fn get(&self) -> Self::Item;
    fn put(&mut self, item: Self::Item);
}​

7. Trait Inheritance : Traits can inherit from other traits, specifying additional requirements or providing new methods. This allows for building trait hierarchies and organizing related functionality.
trait Printable {
    fn print(&self);
}

trait Debuggable: Printable {
    fn debug(&self);
}​

Traits are a powerful feature in Rust that promote code reuse, modularity, and generic programming. They provide a way to define shared behavior and enable polymorphism by allowing different types to implement the same set of methods.
Advertisement