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

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;
主站蜘蛛池模板: 苍南县| 米脂县| 涪陵区| 正宁县| 新竹市| 衡东县| 黄浦区| 定日县| 双柏县| 自治县| 蓝山县| 玉环县| 松潘县| 江孜县| 上饶县| 图木舒克市| 镶黄旗| 玛沁县| 湖北省| 安泽县| 铜鼓县| 札达县| 敦化市| 莒南县| 荥经县| 太谷县| 上饶市| 苍山县| 肥城市| 宁晋县| 东阳市| 营口市| 莒南县| 南汇区| 高青县| 许昌县| 观塘区| 碌曲县| 安新县| 盐山县| 米易县|