How to Implement the Repository Pattern in Rust

Implement the Repository Pattern in Rust by defining a trait for data operations and a struct that implements it using generics.

Implement the Repository Pattern in Rust by defining a trait for data operations and a struct that implements it, using generics and traits as shown in the Rust book's sections on generics and OOP design patterns.

trait Repository<T> {
    fn get(&self, id: i32) -> Option<T>;
    fn save(&mut self, item: T);
}

struct InMemoryRepository<T> {
    items: Vec<T>,
}

impl<T> Repository<T> for InMemoryRepository<T> {
    fn get(&self, _id: i32) -> Option<T> {
        None
    }
    fn save(&mut self, item: T) {
        self.items.push(item);
    }
}

This pattern separates data access logic from business logic, allowing you to swap implementations (e.g., in-memory vs. database) without changing the rest of your code.