Why do I need to double-check / shade when I have a variable variable?

Why do I need to double-check / shade when I can change a variable of a variable? Consider:

let x = a();
let x = b(x);

against.

let mut x = a();
x = b(x);

Interconnected variable binding allows the variable borrowing of this variable over it. But are there any advantages in tenerizing over volatile bindings?

+4
source share
2 answers

Because they have completely different effects.


To understand what is happening, we need to start from the very beginning: what is a binding? What does binding mean?

Consider a simple function: fn hello() -> String;.

When calling this function:

fn main() {
    hello();
}

What's happening?

String, ( Drop, ).

, , , , 1.

, , ... .

fn main() {
    let value = hello();

    std::mem::drop(value);

    println!("{}", value); // Error: moved out of value
}

- : Rust .

, : ( ).

fn main() {
    let x;
    {
        let y = hello();
        x = y;
    }
    println!("{}", x);
}

1 , _.


, , , .

, :

fn main() {
    let x = a();
    let x = b();
}

:

  • a() , x
  • b() , x
  • , b(),
  • , a(),

, , x , .

, b() y, , x , y - .

:

fn main() {
    let mut x = a();
    x = b();
}

:

  • a() , x
  • b() , x, ( a())
  • , b(),

, , , ( ), , .

+8

, : shadowing .

let x = get_some_string();
let x = x.smart_parse_int();
+8

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


All Articles