變量綁定是指將一些值綁定到一個名字上,這樣能夠在以後使用他們。Rust 中使用 let 聲明一個綁定:golang
fn main() { let x = 123; }
綁定默認是不可變的(immutable)。下面的代碼將不能編譯:安全
let x = 123; x = 456;
編譯器會給出以下錯誤:this
Compiling hello_world v0.1.0 (yourpath/hello_world) error[E0384]: re-assignment of immutable variable `x` --> main.rs:3:5 | 2 | let x = 123; | - first assignment to `x` 3 | x = 456; | ^^^^^^^ re-assignment of immutable variable
若是想使得綁定是可變的,使用 mut:debug
let mut x = 123; x = 456;
若是你聲明瞭一個可變綁定而又沒有改變它,雖然能夠編譯經過,但編譯器仍是會給出一些建議和警告:code
let mut x = 123; Compiling hello_world v0.1.0 (yourpath/hello_world) warning: unused variable: `x`, #[warn(unused_variables)] on by default --> main.rs:2:9 | 2 | let mut x = 123; | ^^^^^ warning: variable does not need to be mutable, #[warn(unused_mut)] on by default --> main.rs:2:9 | 2 | let mut x = 123; | ^^^^^ Finished debug [unoptimized + debuginfo] target(s) in 0.63 secs
這正是 Rust 出於安全的目的。orm
Rust 變量綁定有另外一個不一樣於其餘語言的方面:綁定要求在可使用它以前必須初始化。get
例如如下代碼:編譯器
fn main() { let x: i32; println!("Hello world!"); }
Rust 會警告咱們從未使用過這個變量綁定,可是由於咱們從未用過它,無害不罰。it
Compiling hello_world v0.1.0 (yourpath/hello_world) warning: unused variable: `x`, #[warn(unused_variables)] on by default --> main.rs:2:9 | 2 | let x: i32; | ^ Finished debug [unoptimized + debuginfo] target(s) in 0.29 secs
然而,若是確實想使用 x, 事情就不同了。修改代碼:io
fn main() { let x: i32; println!("The value of x is: {}", x); }
這是沒法經過編譯的:
Compiling hello_world v0.1.0 (yourpath/hello_world) error[E0381]: use of possibly uninitialized variable: `x` --> main.rs:3:39 | 3 | println!("The value of x is: {}", x); | ^ use of possibly uninitialized `x` <std macros>:2:27: 2:58 note: in this expansion of format_args! <std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>) main.rs:3:5: 3:42 note: in this expansion of println! (defined in <std macros>) error: aborting due to previous error error: Could not compile `hello_world`.
Rust 不容許咱們使用一個未經初始化的綁定。
在許多語言中,這叫作變量。不過 Rust 的變量綁定有一些不一樣的巧妙之處。例如 let語句的左側是一個「模式」,而不單單是一個變量。咱們也能夠這樣寫:
let (x, y) = (1, 2);
在這個語句被計算後,x 將會是1,'y' 將會是2。也許有人會忍不住說:這不相似於 golang 中的多變量綁定嘛。
var x, y = 1, 2
事實上不是這樣的。(1, 2)這種形式是一個元組,是一個固定大小的有序列表。上面的例子還能夠寫成如下形式:
let n = (1, "hello"); let (x, y) = n;
第一個let將一個元組(1, "hello")綁定到n上,第二個let將元組解構,將元組中的字段綁定到x和y上。
更多模式和元組(Tuple)的特性,將在後續的章節詳細介紹。
Rust 是一個靜態類型語言,意味着咱們須要先肯定咱們須要的類型。事實上,Rust 有一個叫作類型推斷的功能,若是它能確認這是什麼類型,就不須要明確指定類型。固然也能夠顯示的標註類型, 類型寫在一個冒號':'後面:
let x: i32 = 123;
對於數值類型,也能夠這樣:
let x = 123i32; // let x: i32 = 123 let y = 123_i32; // let y: i32 = 123 let z = 100_000i32; // let z: i32 = 100000