Vanya Agnesandra

Rust Endofunctor


This snippet captures a lot of things that I struggle to remember as I learn rust.

struct MyBox {
    thing: i32,
}

impl MyBox {
    fn create(thing: i32) -> MyBox {
        MyBox {
            thing: thing
        }
    }
    fn mutato(self: MyBox, mutator: fn (i32)->i32) -> MyBox {
        MyBox::create(mutator(self.thing))
    }
}

fn main() {
    println!("Hello, world!");
    let boxy: MyBox = MyBox::create(9i32);
    println!("{}", boxy.thing);
    let new_thing: MyBox = boxy.mutato(|u| u * 2);
    println!("{}", new_thing.thing);
}

Hello, world!
9
18

Since mutato doesn’t have to consume the struct, it probably shouldn’t.