Created
January 8, 2019 08:09
-
-
Save rust-play/3065e4cc82a6c4dbc35f7cee0c2d8695 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//! この方法の方でCakeパターンをするとintellij-rustでの補完が効くケースが多い。 | |
type Error = Box<std::error::Error>; | |
#[derive(Debug, Clone, Copy)] | |
struct EmployeeId(u64); | |
#[derive(Debug)] | |
struct Employee { | |
id: EmployeeId, | |
name: String, | |
} | |
trait DataStore { | |
fn get_employee_by_id(&self, id: EmployeeId) -> Result<Employee, Error>; | |
} | |
trait HaveDataStore<D: DataStore> { | |
fn dao(&self) -> &D; | |
} | |
trait Repository<D: DataStore> { | |
fn get_employee(&self, id: EmployeeId) -> Result<Employee, Error>; | |
fn does_employee_exist(&self, id: EmployeeId) -> Result<bool, Error>; | |
} | |
impl<T, D> Repository<D> for T | |
where | |
D: DataStore, | |
T: HaveDataStore<D>, | |
{ | |
fn get_employee(&self, id: EmployeeId) -> Result<Employee, Error> { | |
self.dao().get_employee_by_id(id) | |
} | |
fn does_employee_exist(&self, id: EmployeeId) -> Result<bool, Error> { | |
self.get_employee(id).map(|_| true) | |
} | |
} | |
#[derive(Debug, Default)] | |
struct Dao; | |
impl DataStore for Dao { | |
fn get_employee_by_id(&self, _: EmployeeId) -> Result<Employee, Error> { | |
Ok(Employee { | |
id: EmployeeId(1), | |
name: "ほげ 太郎".to_string(), | |
}) | |
} | |
} | |
#[derive(Debug)] | |
struct Dao2; | |
impl DataStore for Dao2 { | |
fn get_employee_by_id(&self, _: EmployeeId) -> Result<Employee, Error> { | |
Ok(Employee { | |
id: EmployeeId(2), | |
name: "ほげ 太郎2".to_string(), | |
}) | |
} | |
} | |
#[derive(Debug)] | |
struct MyRepository<D>(D); | |
impl<D: DataStore> MyRepository<D> { | |
fn new(dao: D) -> MyRepository<D> { | |
MyRepository(dao) | |
} | |
} | |
impl<D: DataStore> HaveDataStore<D> for MyRepository<D> { | |
fn dao(&self) -> &D { | |
&self.0 | |
} | |
} | |
fn main() { | |
let r = MyRepository::new(Dao); | |
let id = EmployeeId(1); | |
println!("{:?}", r.get_employee(id).unwrap()); | |
println!("{:?}", r.does_employee_exist(id).unwrap()); | |
let r = MyRepository::new(Dao2); | |
let id = EmployeeId(1); | |
println!("{:?}", r.get_employee(id).unwrap()); | |
println!("{:?}", r.does_employee_exist(id).unwrap()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment