Last active
April 18, 2019 02:03
-
-
Save U007D/e8f53f11ec1b658f097c77a1f53fa7bc to your computer and use it in GitHub Desktop.
Simple Dependency Injection
This file contains hidden or 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
#![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