DEV Community

Cover image for 1-minute brain exercise with clever Rust
Rad Code
Rad Code

Posted on

1-minute brain exercise with clever Rust

Tired of reading long Rust documentation? Learn how smart Rust is in 1 min.
Let’s dive in:

1    let mut x = 10;       // Create a mutable variable
2    let y = &mut x;        // Borrow it mutably
3    println!("{}", x);     // Access the variable directly
4    // println!("{}", y);  // Uncommenting this will cause an error in line 3!
Enter fullscreen mode Exit fullscreen mode

Here’s the cool part:

  • Line 3 prints x just fine.
  • But if you uncomment line 4, Rust will throw an error at line 3. Why? Because Rust checks if y will be used later, and if it will, it blocks access to x, as immutable borrow at line 3 can’t happen while y is still valid in scope.

Pretty clever, right?

Top comments (1)

Collapse
 
realactioner profile image
Real Actioner

Haha, yes, it is!