Rust 学习笔记二

注:rust 目前更新仍旧很频繁,语法变化比较大,学习主要基于 Rust 1.0 Alpha 版本,之后可能会有部分变化。

补充下笔记一中的内容:在 Rust 中变量默认是不能改变的,只有声明为 mut,才可以进行改变。

比如:

let x = 5;
x = 7;

会报错 re-assignment of immutable variable,不过下面的方法就可以正常执行了:

let mut x = 5;
x = 7;

逻辑控制

一般逻辑控制分为判断分支、循环等等. if 在 rust 中区别不是特别大:

let x = 5;
if x == 5 {println!("x is five!");} else {println!("x is not five :(");}

不过还可以这样写:

let x = 5;
let y = if x == 5 {10} else {15}; // y: i32

值得注意的是,下面的写法是不正确的:

let x = 5;
let y: i32 = if x == 5 {10;} else {15;};

但是 for 循环区别就比较大了:

for x in range(0, 10) {println!("{}", x); // x: i32
}

while 循环则可以更加简单:

let mut x = 5u;       // mut x: uint
let mut done = false; // mut done: bool

while !done {
    x += x - 3;
    println!("{}", x);
    if x % 5 == 0 {done = true;}
}

如果是要求死循环,使用 loop{} 更加方便。在循环中可以使用 breakcontinue 控制流程进度,这个没什么区别就不再说了。

复杂类型

Rust 作为更先进的编程语言,一些复杂变量类型肯定是支持的,比如 TuplesStructsEnums 等等。

let x = (1,"hello"); // or let x: (i32, &str) = (1,"hello");
struct Point {
    x: i32,
    y: i32,
}
let mut point = Point {x: 0, y: 0};
enum Ordering {
    Less,
    Equal,
    Greater,
}
Ordering::Less
let a = [1, 2, 3];
println!("a has {} elements", a.len());
for e in a.iter() {println!("{}", e);
}
println!("{}", a[0]);

值得一提的是 :: 表示的命名空间,这点和 c 有一些区别。

除此之外,Rust 自定义了一些类型,一种是介于 tuple 和 struct 之间的类型,比如:

struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
let black  = Color(0, 0, 0);
let origin = Point(0, 0, 0);

还有一种叫向量:

let mut nums = vec![1, 2, 3]; 
nums.push(4);

有点像队列,可变商都,可以 push 进行添加。

还有一种切片:

let a = [0, 1, 2, 3, 4];
let middle = a.slice(1, 4);     // A slice of a: just the elements [1,2,3]

for e in middle.iter() {println!("{}", e);          // Prints 1, 2, 3
}

Match

这个也是 Rust 特有的,有点类似 switch 的感觉:

let x = 5;

match x {1 => println!("one"),
    2 => println!("two"),
    3 => println!("three"),
    4 => println!("four"),
    5 => println!("five"),
    _ => println!("something else"),
}

但是 Rust 一定要有最后一行,否则会编译报错。

字符串类型

Rust 的字符串默认是 UTF-8 编码,但是有两种类型的字符串 & str 和 String。这两种类型下面的方式比较:

let a = "aaa"; //a: &str
let b = a.to_string(); // b: String
let c = b.to_slice(); //c: &str

&str 和 String 的区别是,&str 更像是 slice,而 String 则是像一个分配过的内存空间字符串,不能够被修改长度(待确认)。String->&str 会比较方便,但是 & str->String 消耗则会比较大。 输入输出

输入是官方库 std::io::stdin()。:: 之前介绍过,是命名空间,相当于 std::io 库里的 stdin 函数。

比如:

use std::io;

fn main() {println!("Type something!");

    let input = io::stdin().read_line().ok().expect("Failed to read line");

    println!("{}", input);
}
Licensed under CC BY-NC-SA 4.0
Built with Hugo
主题 StackJimmy 设计