[][src]Crate detach

Have you ever needed to pass a mutable reference to yourself to a struct member? Now you can! 100% safe rust code.

Examples

You can pass mutable references to self into member structs:

#[macro_use]
extern crate detach;
use detach::prelude::*;

fn main() {
    struct Sub;
    impl Sub {
        pub fn write(&mut self, t: &mut Top) {
            t.0.push_str("test");
        }
    }
    struct Top(pub String, pub Detach<Sub>);
    impl Top {
        pub fn run(&mut self) {
            detach_run!(self.1, |s| s.write(self));
        }
    }
    let mut t = Top("".to_string(), Detach::new(Sub));
    t.run();
    assert_eq!("test", &t.0);
}

You can invoke detach_run! with an exper:

#[macro_use]
extern crate detach;
use detach::prelude::*;

fn main() {
    let mut i = Detach::new(42_i8);
    detach_run!(i, |z| z = 3);
    assert_eq!(3, *i);
}

You can invoke detach_run! with a block:

#[macro_use]
extern crate detach;
use detach::prelude::*;

fn main() {
    let mut i = Detach::new(42_i8);
    detach_run!(i, |z| {
        z = 3;
    });
    assert_eq!(3, *i);
}

You can return info from the macro:

#[macro_use]
extern crate detach;
use detach::prelude::*;

fn main() {
    let mut i = Detach::new(42_i8);
    let z = detach_run!(i, |z| {
        z = 3;
        return z;
    });
    assert_eq!(3, *i);
    assert_eq!(3, z);
}

You cannot use ? directly (we wouldn't re-attach the member):

This example deliberately fails to compile
#[macro_use]
extern crate detach;
use detach::prelude::*;

fn main() {
    let mut i = Detach::new(42_i8);
    detach_run!(i, |z| {
        z = 3;
        let r: Result<(), ()> = Ok(());
        // THIS WON'T COMPILE:
        r?;
    });
    assert_eq!(3, *i);
}

But you can return results, and ? after the macro:

#[macro_use]
extern crate detach;
use detach::prelude::*;

fn test() -> Result<(), ()> {
    let mut i = Detach::new(42_i8);
    detach_run!(i, |z| {
        z = 3;
        let r: Result<(), ()> = Ok(());
        return r;
    })?;
    assert_eq!(3, *i);
    Ok(())
}

fn main() {
    test().unwrap();
}

Modules

prelude

Macros

detach_run

Structs

Detach

Allows sub-struct to be easily detached and re-attached