News for hackers. Stuff that matters.
Re:Python with Braces by mplanchard on Monday July 08, 2024 @02:12PM (#40907763)
This kind of thing is useful for memory management. Anything you allocate within the scope that isn't returned gets dropped at the end.

You can use this to e.g. acquire a Mutex guard, move/clone something out of the mutex, and ensure it gets dropped as quickly as possible.

    let x = {
        let items = vec![1, 2, 3];
        items[1] // copied out of the vec since usize implements the Copy trait
        // compiler inserts drop(items) here
    };
    // items is no longer valid
    assert_eq!(2, x);
It also comes up in if/else blocks, which have exactly the same syntax and semantics (i.e. they are expressions, not statements):

    let condition = true;
    let x = if condition {
        println!("condition is true");
        5
    } else {
        println!("condition is false");
        10
    };
    assert_eq!(5, x);
edit: and of course, function blocks work exactly the same way! It's neat.

There are no comments on this comment yet.