Rust 变量

变量声明

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

type annotations

Rust 是强类型语言,我们可以在声明变量时指定类型,在编译的时候会被检查。

x类型是 int 32位类型变量
i 表示有符号,u表示无符号整数 ,在Rust中可以声明 8 、 16、 32、 64位的整数

let x: i32 = 5;

let y = 5; //默认是 i32

Mutability

Rust 中如果不特别标示,声明的变量都是不可变得

let x = 5;
x = 10; //这会编译错误

错误如下:


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

如果需要使用可变变量,需要用到 mut 关键字

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

变量初始化

Rust 要求在使用变量前必须对变量进行初始化

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

编译会被 warn,但是依然会打印出 hello world


  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;
                      ^

但是如果使用时,编译器就会报错

fn main() {
    let x: i32;

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

错误如下:


 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

瞬间有种在使用脚本语言的感觉。

posted @ 2016-04-29 16:52  傾聽雨落  阅读(286)  评论(0编辑  收藏  举报