Created
July 23, 2020 07:07
-
-
Save andrewwebber/074bd56417b140b090f323657bc785f0 to your computer and use it in GitHub Desktop.
Rust concerns
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
mod models { | |
#[derive(Debug, serde::Serialize)] | |
pub struct Contact { | |
first_name: String, | |
last_name: String, | |
} | |
impl Contact { | |
pub fn new(first_name: &str, last_name: &str) -> Self { | |
Self { | |
first_name: first_name.to_owned(), | |
last_name: last_name.to_owned(), | |
} | |
} | |
} | |
} | |
mod usecases { | |
pub struct Contacts {} | |
impl Contacts { | |
pub fn create( | |
contact: crate::models::Contact, | |
repo: &impl crate::repo::Repository<crate::models::Contact>, | |
) -> Result<crate::models::Contact, Box<dyn std::error::Error>> { | |
repo.set(contact) | |
} | |
} | |
} | |
mod repo { | |
pub trait Repository<T> { | |
fn set(&self, obj: T) -> Result<T, Box<dyn std::error::Error>>; | |
} | |
} | |
struct FileRepository { | |
path: String, | |
} | |
impl FileRepository { | |
fn new(path: &str) -> FileRepository { | |
FileRepository { | |
path: path.to_owned(), | |
} | |
} | |
} | |
impl<T: serde::Serialize> crate::repo::Repository<T> for FileRepository { | |
fn set(&self, obj: T) -> Result<T, Box<dyn std::error::Error>> { | |
use std::fs::File; | |
let f = File::create(&self.path)?; | |
serde_json::to_writer(f, &obj).expect("Unable to serialized"); | |
Ok(obj) | |
} | |
} | |
fn main() -> Result<(), Box<dyn std::error::Error>> { | |
let repo = FileRepository::new("/tmp/foo.json"); | |
let contact = models::Contact::new("andrew", "webber"); | |
crate::usecases::Contacts::create(contact, &repo)?; | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment