Skip to content
On this page

变量1:exercises/variables/variables1.rs

题目

rust
// variables1.rs
//
// Make me compile!
//
// Execute `rustlings hint variables1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

fn main() {
    x = 5;
    println!("x has the value {}", x);
}

题目解析

错误提示信息如下:

txt
⚠️  Compiling of exercises/variables/variables1.rs failed! Please try again. Here's the output:
error[E0425]: cannot find value `x` in this scope
  --> exercises/variables/variables1.rs:11:5
   |
11 |     x = 5;
   |     ^
   |
help: you might have meant to introduce a new binding
   |
11 |     let x = 5;
   |     +++

error[E0425]: cannot find value `x` in this scope
  --> exercises/variables/variables1.rs:12:36
   |
12 |     println!("x has the value {}", x);
   |                                    ^ not found in this scope

error: aborting due to 2 previous errors

首先提示我们可能时要引入一个新的绑定,建议我们添加let关键字,并提示x在当前作用域下未找到。

正是如此,如果我们要创建一个变量,必须使用let语句。

所以修改后如下:

rust
fn main() {
    x = 5; 
    let x = 5; 
    println!("x has the value {}", x);
}

笔记

所有的变量创建,都需要使用let进行绑定。

参考资料

Powered by VitePress