- Rust Programming By Example
- Guillaume Gomez Antoni Boucher
- 188字
- 2021-07-02 19:12:56
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;
推薦閱讀
- 中國人民大學(xué)復(fù)印報刊資料轉(zhuǎn)載指數(shù)排名研究報告2016
- 面向青少年的博物館教育(上下卷)
- 檔案社會控制功能研究
- 圖書館服務(wù)思維研究
- 醫(yī)學(xué)文獻(xiàn)管理
- 高校圖書館閱讀推廣與宣傳促進(jìn)研究
- 現(xiàn)代圖書館全面質(zhì)量管理與創(chuàng)新服務(wù)研究
- 河南省博物院鎮(zhèn)館之寶
- 《葉赫那拉氏族譜》整理與研究
- Swift Game Development(Third Edition)
- 信息資源的公共獲取機(jī)制研究
- 西夏檔案及其管理制度研究
- 北疆博物院的故事
- 近代中國的學(xué)術(shù)與藏書
- 茶與咖啡:張信剛文化與經(jīng)濟(jì)講座