官术网_书友最值得收藏!

Variables

We'll now change the previous program to add a variable:

fn main() {
    let name = "world";
    println!("Hello, {}!", name);
}

The {} part in the string literal is replaced by the content of the name variable. Here, we see the type inference in action—we don't have to specify the type of the name variable and the compiler will infer it for us. We could have also written the type ourselves:

let name: &str = "world";

(From now on, I'll omit the main function, but this code should be written inside the function.)

In Rust, variables are immutable by default. As such, writing the following will cause a compile-time error:

let age = 42;
age += 1;

The compiler gives us a very helpful error message:

error[E0384]: cannot assign twice to immutable variable `age`
  --> src/main.rs:16:5
   |
15 |     let age = 42;
   |         --- first assignment to `age`
16 |     age += 1;
   |     ^^^^^^^^ cannot assign twice to immutable variable

To make a variable mutable, we need to use the mut keyword:

let mut age = 42;
age += 1;
主站蜘蛛池模板: 靖宇县| 开封县| 鄂托克前旗| 靖州| 青冈县| 新津县| 隆安县| 新和县| 绍兴市| 信丰县| 洞头县| 杭州市| 双柏县| 家居| 金平| 台东县| 延津县| 吉安县| 寿光市| 安顺市| 新和县| 阿坝县| 新邵县| 乌兰县| 通道| 芷江| 达拉特旗| 邓州市| 诸暨市| 南乐县| 海原县| 荥阳市| 岳阳县| 彰化市| 武功县| 高雄县| 青冈县| 厦门市| 保靖县| 革吉县| 鄂尔多斯市|