Câu hỏi phỏng vấn Rust
Câu hỏi

Explain what is Trait in Rust? What are some use cases when you need to implement one?

Câu trả lời

In Rust, a trait is a language feature that defines a set of methods that a type must implement. Traits are similar to interfaces in other programming languages like Java or Go, but they also have some unique characteristics. They allow for the definition of shared behavior across different types, promoting code reuse and type safety.

Defining a Trait

A trait is defined using the trait keyword followed by the trait name and a block containing method signatures. Here is a simple example:

pub trait MyTrait {
    fn some_method(&self) -> String;
}

In this example, MyTrait is a trait that requires any type implementing it to define the some_method function.

Implementing a Trait

To implement a trait for a specific type, you use the impl keyword followed by the trait name and the type:

struct MyStruct;

impl MyTrait for MyStruct {
    fn some_method(&self) -> String {
        "Hello from MyStruct".to_string()
    }
}

Use Cases for Traits

  1. Shared Behavior Across Types: Traits allow you to define methods that can be shared across different types. For example, you might have a Printable trait that requires a print method, which can be implemented for various types like Person and Car:

    trait Printable {
        fn print(&self);
    }
    
    struct Person {
        name: String,
        age: u32,
    }
    
    impl Printable for Person {
        fn print(&self) {
            println!("Person {{ name: {}, age: {} }}", self.name, self.age);
        }
    }
    
    struct Car {
        make: String,
        model: String,
    }
    
    impl Printable for Car {
        fn print(&self) {
            println!("Car {{ make: {}, model: {} }}", self.make, self.model);
        }
    }
  2. Generic Programming: Traits are essential for generic programming in Rust. They allow you to write functions and structs that can operate on any type that implements a particular trait. For example, a function that prints any Printable type:

    fn print_thing<T: Printable>(thing: &T) {
        thing.print();
    }
  3. Marker Traits: These are traits that do not have any methods but are used to mark types with certain properties. For example, the Send and Sync traits in Rust are marker traits that indicate whether a type can be safely transferred or accessed across threads.

  4. Conditional Implementations: Traits can be used to provide conditional implementations. For example, you can implement a t...

middle

middle

Gợi ý câu hỏi phỏng vấn

senior

Explain the use of Fn / FnMut / FnOnce family of traits in Rust

junior

What happens when you pass a String to a function in Rust?

middle

What does Rust have instead of a Garbage Collector?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào