rust 语法速记 - WinChua/blog GitHub Wiki

variable && mutability

fn main() {
  let x = 5; // 不可变
  // x = 6;  // compile error, x 是immut
  let x = 6; // 重新定义x
  let mut x = 6; // 重新定义x, 且x是可变的
  x = 9;
}

const

const three : u32 = 32;

compound type

  • tuple type
let x = (1, 2); // rust 会进行类型推导, x: (i32, i32)
let tup: (i32, u32, f32) = (-1, 2, 0.2);
println!("tup.0 is {}, tup.1 is s{}, tup.2 is {}", tup.0, tup.1, tup.2);
  • array type
let a: [i32; 5] = [1,2,3,4,5];
let a = [1,2,3,4,5];
let a = [3; 5];
println!("a[0] is {}", a[0]);

function

fn func(x: i32, mut y: i32) -> i32 {
    x + y
}
  • statement && expression
fn func(x: i32, mut y: i32) -> i32 {
    y = x * y + 32; // statement
    x + y // expression, it also used as the return value for the func
}

control flow

  • while 用于循环控制副作用, loop用于产生值
  • if expression
let x = if arg > 5 { "gt5" } else { "lt5" };
  • repeats with loop, loop 可以用作expression, 用break 返回值
let mut y = 32;
'up: loop {
    y -= 1;
    if y <= 0 {
        break 'up;
    }
}
y = 32;
let data = loop {
    y -= 1;
    if y <= 0 {
        break 42;
    }
}
  • conditional loop with while, while 不可用作表达式, 返回 ()
let mut y = 32;
while y > 0 {
 y -= 1;
}
  • loop through collection with for

mut的使用

上下文 示例 作用
变量绑定 let mut x = 5; 允许修改变量值
可变引用 let r = &mut s; 允许通过引用修改数据
函数参数 fn f(s: &mut String) 函数内可修改参数
结构体实例 let mut p = Point { x: 0 }; 允许修改结构体字段
模式匹配 Some(ref mut val) 匹配时获取可变引用
闭包 let mut closure = || {...} 闭包可修改捕获的变量
裸指针 *mut i32 不安全代码中修改指针指向的值
解构绑定 let (mut a, b) = ... 解构时指定可变性
静态变量 static mut X: u32 = 0; 全局可变状态(需 unsafe)