From 152a7a71101b94e4ddaa221396403d7dd1e76dbe Mon Sep 17 00:00:00 2001 From: HampusM Date: Sat, 9 Jul 2022 22:02:15 +0200 Subject: docs: add example --- example/Cargo.toml | 11 ++++++ example/src/main.rs | 112 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 example/Cargo.toml create mode 100644 example/src/main.rs diff --git a/example/Cargo.toml b/example/Cargo.toml new file mode 100644 index 0000000..c80daa3 --- /dev/null +++ b/example/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "example" +version = "0.1.0" +license = "LGPL-2.1" +authors = ["HampusM "] +edition = "2021" + +[dependencies] +syrette = { path = "../syrette" } +error-stack = "0.1.1" + diff --git a/example/src/main.rs b/example/src/main.rs new file mode 100644 index 0000000..920d9f0 --- /dev/null +++ b/example/src/main.rs @@ -0,0 +1,112 @@ +use syrette::{injectable, DIContainer, DIContainerError}; + +trait IDog +{ + fn woof(&self); +} + +struct Dog {} + +#[injectable(IDog)] +impl Dog +{ + fn new() -> Self + { + Self {} + } +} + +impl IDog for Dog +{ + fn woof(&self) + { + println!("Woof!"); + } +} + +trait ICat +{ + fn meow(&self); +} + +struct Cat {} + +#[injectable(ICat)] +impl Cat +{ + fn new() -> Self + { + Self {} + } +} + +impl ICat for Cat +{ + fn meow(&self) + { + println!("Meow!"); + } +} + +trait ICow +{ + fn moo(&self); +} + +trait IHuman +{ + fn make_pets_make_sounds(&self); +} + +struct Human +{ + _dog: Box, + _cat: Box, +} + +#[injectable(IHuman)] +impl Human +{ + fn new(dog: Box, cat: Box) -> Self + { + Self { + _dog: dog, + _cat: cat, + } + } +} + +impl IHuman for Human +{ + fn make_pets_make_sounds(&self) + { + println!("Hi doggy!"); + + self._dog.woof(); + + println!("Hi kitty!"); + + self._cat.meow(); + } +} + +fn main() -> error_stack::Result<(), DIContainerError> +{ + println!("Hello, world!"); + + let mut di_container: DIContainer = DIContainer::new(); + + di_container.bind::().to::(); + di_container.bind::().to::(); + di_container.bind::().to::(); + + let dog = di_container.get::()?; + + dog.woof(); + + let human = di_container.get::()?; + + human.make_pets_make_sounds(); + + Ok(()) +} -- cgit v1.2.3-18-g5258