Skip to content
On this page

变量2:exercises/variables/variables2.rs

题目

rust
// variables2.rs
//
// Execute `rustlings hint variables2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

fn main() {
    let x;
    if x == 10 {
        println!("x is ten!");
    } else {
        println!("x is not ten!");
    }
}

题目解析

编译错误信息如下:

txt
⚠️  Compiling of exercises/variables/variables2.rs failed! Please try again. Here's the output:
error[E0282]: type annotations needed
 --> exercises/variables/variables2.rs:9:9
  |
9 |     let x;
  |         ^
  |
help: consider giving `x` an explicit type
  |
9 |     let x: /* Type */;
  |          ++++++++++++

error: aborting due to previous error

For more information about this error, try `rustc --explain E0282`.

错误信息提示我们应该给变量x一个显式的类型。

rust
fn main() {
    let x; 
    let x: i32; 
    if x == 10 {
        println!("x is ten!");
    } else {
        println!("x is not ten!");
    }
}

出现了新的错误:

txt
⚠️  Compiling of exercises/variables/variables2.rs failed! Please try again. Here's the output:
error[E0381]: used binding `x` isn't initialized
  --> exercises/variables/variables2.rs:10:8
   |
9  |     let x: i32;
   |         - binding declared here but left uninitialized
10 |     if x == 10 {
   |        ^ `x` used here but it isn't initialized
   |
help: consider assigning a value
   |
9  |     let x: i32 = 0;
   |                +++

error: aborting due to previous error

For more information about this error, try `rustc --explain E0381`.

告诉我们变量x声明了绑定,但是没有初始化。在if x == 10处使用了变量x,但是没有初始化。

错误信息也提示我们,应该let x: i32 = 0;进行变量的初始化。

所以应该修改为:

rust
fn main() {
    let x; 
    let x: i32 = 0; 
    if x == 10 {
        println!("x is ten!");
    } else {
        println!("x is not ten!");
    }
}

当然,此处如果我们不定义x的类型,直接使用let x = 0;进行初始化,Rust仍然可以自动推断为i32,所以我们也可以这样改:

rust
fn main() {
    let x; 
    let x = 0; 
    if x == 10 {
        println!("x is ten!");
    } else {
        println!("x is not ten!");
    }
}

笔记

  • rust是静态类型语言,每个变量都有类型
  • 如果不指定类型,Rust编译器会进行自动的推导
  • 变量需要先进行初始化,才能使用

参考资料

Powered by VitePress