首页 > 其他分享 >[Rust] Shadowing

[Rust] Shadowing

时间:2024-02-23 15:15:42浏览次数:19  
标签:don Shadowing variables Number number let println Rust

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);
    }
}

 

标签:don,Shadowing,variables,Number,number,let,println,Rust
From: https://www.cnblogs.com/Answer1215/p/18029546

相关文章

  • [Rust] Handle errors in Rust using Pattern Matching
    Inthislessonwe'llexplorehowtounwrapa Result typeusingalanguagefeaturecalledPatternMatching. usestd::io;fnmain(){letmutfirst=String::new();io::stdin().read_line(&mutfirst).unwrap();letmuta:u32=......
  • [Rust] Exit a program using std::process in Rust
    Inthislessonwe'lllearnhowtoexitaprogramusingthe std::process moduleinRustandit's exit() method. usestd::io;usestd::process;fnmain(){letmutfirst=String::new();io::stdin().read_line(&mutfirst).unwrap()......
  • [Rust] Create a loop in Rust
    ThislessonshowshowtouseaRust loop torunaprograminfinitely. usestd::io;usestd::process;fnmain(){loop{println!("Pleaseenterafirstnumber:");leta=read_user_input();println!("Plea......
  • [Rust] Handle errors in Rust using expect()
    Thislessondiscusseshowtoimproveerrorhandlingbyconfiguringcustomerrormessagesusingthe expect() function. usestd::io;fnmain(){letmutfirst=String::new();io::stdin().read_line(&mutfirst);//Notrecommnedto......
  • [Rust] Char vs String
    usestd::path::PathBuf;useclap::Parser;#[derive(Parser,Debug)]#[clap()]pubstructOpts{pubargs:Vec<String>,#[clap(short='c',long="config")]pubconfig:Option<PathBuf>,#[clap(short='p'......
  • Rust 编译报 spurious network error (1 tries remaining): [7] Couldn't connect to
    现象:当执行 cargobuild时报类似错误:warning:spuriousnetworkerror(3triesremaining):[7]Couldn'tconnecttoserver(Failedtoconnectto127.0.0.1port8899after2040ms:Couldn'tconnecttoserver);class=Net(12)warning:spuriousnetworkerror......
  • Docker 运行图形界面版 aTrust
    1、Docker、Docker-Compose安装https://www.cnblogs.com/a120608yby/p/9883175.htmlhttps://www.cnblogs.com/a120608yby/p/14582853.html2、服务Docker-Compose配置#catdocker-compose.ymlversion:'3'services:atrust:image:hagb/docker-atrustc......
  • [Rust] Reference Types in Rust
    LearnhowtocreatereferencesinRustusingtheborrow-operator & andwhentheyareuseful.Foramorethoroughexplanationofreferencesandtheircharacteristics,checkoutthisblogpost:https://blog.thoughtram.io/references-in-rust/letname:St......
  • [Rust] Arrays in Rust
    InthislessonwetakealookatArraysandthedifferentwaysofcreatingthem.ArraysinRustarecollectionsofvaluesofthesametypethatcannotchangeinsize.Inotherwords,thenumberoffields(orelements)hastobeknownatcompiletime.#[al......
  • [Rust] Vectors in Rust
    Inthislessonyou'lllearnabout Vec<T>,or Vectors.VectorsarelikeArrays,acollectionofvaluesofthesametype,butasopposedtoArrays,Vectorscanchangeinsize.#[allow(warnings)]fnmain(){letmutnumbers=vec![1,4];......