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

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

相关文章
相关标签/搜索