simple/
simple.rs

1use resman::Resources;
2
3#[cfg_attr(feature = "debug", derive(Debug))]
4struct A(u32);
5
6#[cfg_attr(feature = "debug", derive(Debug))]
7struct B(u32);
8
9fn main() {
10    let mut resources = Resources::default();
11
12    resources.insert(A(1));
13    resources.insert(B(2));
14
15    // We can validly have two mutable borrows from the `Resources` map!
16    let mut a = resources.borrow_mut::<A>();
17    let mut b = resources.borrow_mut::<B>();
18    a.0 = 2;
19    b.0 = 3;
20
21    // We need to explicitly drop the A and B borrows, because they are runtime
22    // managed borrows, and rustc doesn't know to drop them before the immutable
23    // borrows after this.
24    drop(a);
25    drop(b);
26
27    // Multiple immutable borrows to the same resource are valid.
28    let a_0 = resources.borrow::<A>();
29    let _a_1 = resources.borrow::<A>();
30    let b = resources.borrow::<B>();
31
32    println!("A: {}", a_0.0);
33    println!("B: {}", b.0);
34
35    // Trying to mutably borrow a resource that is already borrowed (immutably
36    // or mutably) returns `Err`.
37    let a_try_borrow_mut = resources.try_borrow_mut::<A>();
38    let exists = if a_try_borrow_mut.is_ok() {
39        "Ok(..)"
40    } else {
41        "Err"
42    };
43    println!("a_try_borrow_mut: {}", exists); // prints "Err"
44}