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

How would you model a Many-to-Many relationship with a Reference-Counted Smart Pointer in Rust?

Câu trả lời

To model a many-to-many relationship with a reference-counted smart pointer in Rust, you can use the Rc<T> type, which stands for Reference Counted. This type allows multiple ownership of the same data, making it suitable for scenarios where multiple entities need to share ownership of the same resource. Here’s a step-by-step explanation and example of how you can achieve this:

Step-by-Step Explanation

  1. Define the Entities: Create structs to represent the entities involved in the many-to-many relationship. For example, if you are modeling a relationship between Student and Course, you would define these structs.

  2. Use Rc<T> for Shared Ownership: Use Rc<T> to allow multiple Student instances to own the same Course instance and vice versa.

  3. Establish the Relationship: Use vectors of Rc<T> within each struct to hold references to the related entities.

Example Code

Here’s an example of how you might model a many-to-many relationship between Student and Course:

use std::rc::Rc;

#[derive(Debug)]
struct Student {
    name: String,
    courses: Vec<Rc<Course>>,
}

#[derive(Debug)]
struct Course {
    title: String,
    students: Vec<Rc<Student>>,
}

impl Student {
    fn new(name: &str) -> Rc<Self> {
        Rc::new(Student {
            name: name.to_string(),
            courses: Vec::new(),
        })
    }

    fn enroll(&mut self, course: Rc<Course>) {
        self.courses.push(course);
    }
}

impl Course {
    fn new(title: &str) -> Rc<Self> {
        Rc::new(Course {
            title: title.to_string(),
            students: Vec::new(),
        })
    }

    fn add_student(&mut self, student: Rc<Student>) {
        self.students.push(student);
    }
}

fn main() {
    // Create students
    let student1 = Student::new("Alice");
    let student2 = Student::new("Bob");

    // Create courses
    let course1 = Course::new("Math");
    let course2 = Course::new("Science");

    // Enroll students in courses
    Rc::get_mut(&mut student1.clone()).unwrap().enroll(course1.clone());
    Rc::get_mut(&mut student1.clone()).unwrap().enroll(course2.clone());
    Rc::get_mut(&mut student2.clone()).unwrap().enroll(course1.clone());

    // Add students to courses
    Rc::get_mut(&mut course1.clone()).unwrap().add_student(student1.clone());...
middle

middle

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

senior

Explain what is Send and Sync in Rust and when do you need them?

middle

When can’t my type be Copy 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