Rust 變量

變量聲明

let x=5;
let (x,y) = (1,2); //x=1 y=2

type annotations

Rust 是強類型語言,咱們能夠在聲明變量時指定類型,在編譯的時候會被檢查。ruby

x類型是 int 32位類型變量
i 表示有符號,u表示無符號整數 ,在Rust中能夠聲明 8 、 1六、 3二、 64位的整數markdown

let x: i32 = 5;

let y = 5; //默認是 i32

Mutability

Rust 中若是不特別標示,聲明的變量都是不可變得ui

let x = 5;
x = 10; //這會編譯錯誤

錯誤以下:spa

error: re-assignment of immutable variable `x`
     x = 10;
     ^~~~~~~

若是須要使用可變變量,須要用到 mut 關鍵字翻譯

let mut x =5; //mut x: i32
x = 10;

變量初始化

Rust 要求在使用變量前必須對變量進行初始化code

fn main(){
    let x: i32;
    println!("hello world !!!");
}

編譯會被 warn,可是依然會打印出 hello worldregexp

Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)]
   on by default
src/main.rs:2     let x: i32;
                      ^

可是若是使用時,編譯器就會報錯orm

fn main() {
    let x: i32;

    println!("The value of x is: {}", x);
}

錯誤以下:xml

Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x`
src/main.rs:4     println!("The value of x is: {}", x);
                                                    ^
note: in expansion of format_args!
<std macros>:2:23: 2:77 note: expansion site
<std macros>:1:1: 3:2 note: in expansion of println!
src/main.rs:4:5: 4:42 note: expansion site
error: aborting due to previous error
Could not compile `hello_world`.

變量做用域

{} 表示一個代碼塊,代碼塊內的變量 不能做用於代碼塊外!作用域

fn main() {
    let x: i32 = 17;
    {
        let y: i32 = 3;
        println!("The value of x is {} and value of y is {}", x, y);
    }
    println!("The value of x is {} and value of y is {}", x, y); // This won't work
}

Rust 有一個變態的功能,官方文檔中稱爲 shadow,不知道如何翻譯,看下代碼就明白了

let x: i32 = 8;
{
    println!("{}", x); // Prints "8"
    let x = 12;
    println!("{}", x); // Prints "12"
}
println!("{}", x); // Prints "8"
let x =  42;
println!("{}", x); // Prints "42"

同一名稱的變量能夠被重複聲明。挺酷的一特性,可是是把雙刃劍,弄好好會割傷本身
這種重複變量聲明的特性,也能夠改變變量的類型。

let mut x: i32 = 1;
x = 7;
let x = x; // x is now immutable and is bound to 7

let y = 4;
let y = "I can also be bound to text!"; // y is now of a different type

瞬間有種在使用腳本語言的感受。

相關文章
相關標籤/搜索