- 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;
推薦閱讀
- 北大中文系第一課
- 公共圖書館文獻(xiàn)信息資源政府采購
- 國外圖書館動漫資源建設(shè)與服務(wù)
- 中國古代圖書館學(xué)研究
- 從私藏到公共展覽:民國時期廣州的博物館和展覽會
- 醫(yī)藥信息處理與分析
- 檔案利用與服務(wù)
- 中國古典文獻(xiàn)學(xué)(東北師范大學(xué)文學(xué)院學(xué)術(shù)史文庫)
- 法學(xué)研究與文獻(xiàn)檢索
- 大學(xué)圖書館信息服務(wù)與信息素養(yǎng)教育理論與實踐研究
- 基于價值全面實現(xiàn)的檔案信息資源配置
- 陜西古代文獻(xiàn)研究(第一輯)
- 數(shù)字資源存儲、倉儲和發(fā)布的標(biāo)準(zhǔn)規(guī)范建設(shè)
- 專利計量與專利合作
- 兒童閱讀的世界Ⅳ:學(xué)校、家庭與社區(qū)的實踐研究