[Rust] Shadowing

Ref to : https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing

 

fn main() {
    let number = "T-H-R-E-E"; // don't change this line
    println!("Spell a Number : {}", number);
    number = 3; // don't rename this variable
    println!("Number plus two is : {}", number + 2);
}

We have compile error:

⚠️  Compiling of exercises/variables/variables5.rs failed! Please try again. Here's the output:
error[E0308]: mismatched types
 --> exercises/variables/variables5.rs:9:14
  |
7 |     let number = "T-H-R-E-E"; // don't change this line
  |                  ----------- expected due to this value
8 |     println!("Spell a Number : {}", number);
9 |     number = 3; // don't rename this variable
  |              ^ expected `&str`, found integer

error[E0369]: cannot add `{integer}` to `&str`
  --> exercises/variables/variables5.rs:10:48
   |
10 |     println!("Number plus two is : {}", number + 2);
   |                                         ------ ^ - {integer}
   |                                         |
   |                                         &str

error: aborting due to 2 previous errors

 

Let use shadowing:

fn main() {
    let number = "T-H-R-E-E"; // don't change this line
    println!("Spell a Number : {}", number);
    {
        let number = 3; // don't rename this variable
        println!("Number plus two is : {}", number + 2);
    }
}

 

posted @ 2024-02-23 14:59  Zhentiw  阅读(8)  评论(0编辑  收藏  举报