Skip to content

Instantly share code, notes, and snippets.

@U007D
Last active April 18, 2019 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save U007D/780613753a2173314d7113ba0619caf2 to your computer and use it in GitHub Desktop.
Save U007D/780613753a2173314d7113ba0619caf2 to your computer and use it in GitHub Desktop.
Getting Started DI example naive Rust implementation from https://autofac.readthedocs.io/en/latest/getting-started/index.html
#![feature(existential_type)]
use chrono::Local;
use std::io::{self, Write};
type Result<T> = std::result::Result<T, failure::Error>;
trait IOutput {
fn write(&self, content: &String) -> Result<()>;
}
struct ConsoleOutput {}
impl ConsoleOutput {
fn new() -> Self { Self {} }
}
impl IOutput for ConsoleOutput {
fn write(&self, content: &String) -> Result<()> {
io::stdout().write(content.as_bytes())?;
Ok(())
}
}
trait IDateWriter {
fn write_date(&self) -> Result<()>;
}
struct TodayWriter<O: IOutput> {
output: O,
}
impl<O: IOutput> TodayWriter<O> {
fn new(output: O) -> Self {
Self { output, }
}
}
impl<O: IOutput> IDateWriter for TodayWriter<O> {
fn write_date(&self) -> Result<()> {
self.output.write(&Local::today()
.format("%b %d, %Y").to_string())
}
}
trait IContainer {
type IOutputType: IOutput;
type IDateWriterType: IDateWriter;
fn resolve_i_output() -> Self::IOutputType;
fn resolve_i_date_writer() -> Self::IDateWriterType;
}
struct Container {}
impl IContainer for Container {
existential type IOutputType: IOutput;
existential type IDateWriterType: IDateWriter;
fn resolve_i_output() -> Self::IOutputType { ConsoleOutput::new() }
fn resolve_i_date_writer() -> Self::IDateWriterType {
TodayWriter::new(Container::resolve_i_output())
}
}
fn main() -> Result<()> {
let writer = Container::resolve_i_date_writer();
writer.write_date()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment