Skip to content

Instantly share code, notes, and snippets.

@U007D
Last active April 18, 2019 02:03
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/e8f53f11ec1b658f097c77a1f53fa7bc to your computer and use it in GitHub Desktop.
Save U007D/e8f53f11ec1b658f097c77a1f53fa7bc to your computer and use it in GitHub Desktop.
Simple Dependency Injection
#![feature(existential_type)]
type Result<T> = std::result::Result<T, failure::Error>;
trait MyTrait {
fn greet(&self) -> String;
}
struct MyType {}
impl MyTrait for MyType {
fn greet(&self) -> String {
String::from("Hello, world!")
}
}
trait Container {
type MyTraitType: MyTrait;
type MyFnType: Fn();
fn resolve_my_trait() -> Self::MyTraitType;
fn resolve_my_fn() -> Self::MyFnType;
}
struct MyContainer;
impl Container for MyContainer {
existential type MyTraitType: MyTrait;
existential type MyFnType: Fn();
fn resolve_my_trait() -> Self::MyTraitType { MyType {} }
fn resolve_my_fn() -> Self::MyFnType { || println!("Yay, works with Voldemort types!") }
}
fn main() -> Result<()> {
let my_type = MyContainer::resolve_my_trait();
println!("{}", my_type.greet());
MyContainer::resolve_my_fn()();
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment