How do rust locks work and how do they close?

Does it create a new thread and then perform this anonymous function inside the new thread?

I noticed a lot of restrictions on ownership / borrowing when I work with closure. For example, if I have Fn(), I can’t pass the volatile variable inside the closure or I need to wrap it withMutex

fn helloworld(f: &Fn(f64)) {
    f(42f64);
}

pub fn main() {
    let mut killer = 2;
    helloworld(&|n| {
        println!("{}", n);
        killer += 1;
    });
}

If closing can be unsafe, then something asynchronous or parallel happens behind the scene and that the Rust compiler does not allow me to compile such code.

I could just be embarrassed, because I'm starting from the world of JavaScript / Python, and everything is completely different there.

+4
source share
1 answer

.

-, Rust - , "" . , :

fn main() {
    let a = 6;
    let closure = |b| {
        println!("product is: {}", a * b);
    };
    closure(7);
}

de-sugared - :

fn main() {
    let a = 6;
    let closure = {
        struct Closure<'a> {
            a: &'a i32,
        }
        impl<'a> Fn<(i32,)> for Closure<'a> {
            extern "rust-call" fn call(&self, (b,): (i32,)) {
                println!("product is: {}", (*self.a) * b);
            }
        }
        impl<'a> FnMut<(i32,)> for Closure<'a> {
            extern "rust-call" fn call_mut(&mut self, args: (i32,)) {
                self.call(args)
            }
        }
        impl<'a> FnOnce<(i32,)> for Closure<'a> {
            type Output = ();
            extern "rust-call" fn call_once(self, args: (i32,)) {
                self.call(args)
            }
        }
        Closure {
            a: &a,
        }
    };
    FnOnce::call_once(closure, (7,));
}

: . ; .

, . "".

, : . , . Fn, FnMut FnOnce ( Fn, FnMut FnOnce?). &Fn(f64), , , .

, , FnMut. , , FnOnce ( -, ).

+10

Source: https://habr.com/ru/post/1684659/


All Articles