Skip to content

Instantly share code, notes, and snippets.

@fujitayy
Forked from rust-play/playground.rs
Created January 8, 2019 08:09
Show Gist options
  • Save fujitayy/496085a3b5d98c41a31355aa72852549 to your computer and use it in GitHub Desktop.
Save fujitayy/496085a3b5d98c41a31355aa72852549 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
//! この方法の方で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