Rust 编程入门

菜鸟入门 rust

Posted by Jerry Chen on June 14, 2020

资料

《Rust 程序设计语言 第二版》

常见编程概念

变量

变量不可变
1
2
3
4
5
fn main() {
    let x = 5;
    println!("x is {}", x);
    x = 6; //报错,因为 x 默认不可变
}
变量可变
1
2
3
4
5
6
fn main() {
    let mut x = 5;
    println!("x is {}", x);
    x = 6; //x 可变
    println!("x is {}", x);
}
变量隐藏

上一个同名 x 变量被隐藏了;

使用 let 就会创建新变量;

1
2
3
4
5
6
fn main() {
    let x = 5;
    println!("x is {}", x);
    let x: String = "hello".parse().expect("Not a string!");
    println!("x is {}", x);
}

常量

1
2
3
4
5
const MAX_POINTS: u32 = 100_000;

fn main() {
    println!("MAX_POINTS is {}", MAX_POINTS);
}

类型

整型

arch 表示系统位数,比如 64-bit;

长度 有符号 无符号
8-bit i8 u8
16-bit i16 u16
32-bit i32 u32
64-bit i64 u64
128-bit i128 u128
arch isize usize
1
2
3
4
5
fn main() {
    let x: i32 = -118;
    println!("x is {}", x);
    println!("max is {}", usize::max_value());
}
浮点型
长度 浮点
32-bit f32
64-bit f64
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
    // 加法
    let sum: i32 = 5 + 10; // 显式指定类型注解
    println!("sum is {}", sum);
    // 减法
    let difference: f32 = 95.5 - 4.3; // 显式指定类型注解
    println!("difference is {}", difference);
    // 乘法
    let product = 4 * 30;
    println!("product is {}", product);
    // 除法
    let quotient = 56.7 / 32.2;
    println!("quotient is {}", quotient);
    // 取余
    let remainder = 43 % 5;
    println!("remainder is {}", remainder);
}
布尔类型

Rust 中的布尔类型(bool)有两个可能的值:truefalse

1
2
3
4
5
6
fn main() {
    let t = true;
    let f: bool = false; // 显式指定类型注解
    println!("t is {}", t);
    println!("f is {}", f);
}
字符类型

Rust 的 char 类型的大小为四个字节(four bytes);

1
2
3
4
5
6
7
8
fn main() {
    let c = 'z';
    let z: char = 'ℤ'; // 显式指定类型注解
    let heart_eyed_cat = '😻';
    println!("c is {}", c);
    println!("z is {}", z);
    println!("heart_eyed_cat is {}", heart_eyed_cat);
}
数组类型
1
2
3
4
5
6
7
8
9
10
11
12
fn main() {
    let a = [1, 2, 3, 4, 5];
    println!("a[0] is {}", a[0]);
    let a: [i32; 5] = [1, 2, 3, 4, 5]; // 显式指定类型注解
    println!("a[4] is {}", a[4]);

    let first = a[0];
    let second = a[1];
    let [x, y, z, m, n] = a; //解构数组
    println!("first is {}", first);
    println!("n is {}", n);
}
元组类型
1
2
3
4
5
6
7
8
9
10
fn main() {
    let x: (i32, f64, u8) = (500, 6.4, 1);
    println!("x.0 is {}", x.0);

    let five_hundred = x.0;
    let six_point_four = x.1;
    let one = x.2;
    let (m, n, z) = x; //解构元组
    println!("z is {}", z);
}

函数

无参数无返回值

Rust 不关心函数定义于何处,只要定义了就行;

1
2
3
4
5
6
7
8
fn main() {
    println!("Hello, world!");
    another_function();
}

fn another_function() {
    println!("Another function.");
}
有参数无返回值
1
2
3
4
5
6
7
fn main() {
    another_function(5);
}

fn another_function(x: i32) {
    println!("x is {}", x);
}
表达式

使用 {} 创建一个作用域,最终结果是一个表达式;

1
2
3
4
5
6
7
8
fn main() {
    let x = 5;
    let y = {
        let x = 3;
        x + 1
    };
    println!("y is {}", y);
}
无参数有返回值
1
2
3
4
5
6
7
8
fn five() -> i32 {
    5
}

fn main() {
    let x = five();
    println!("x is {}", x);
}
有参数有返回值
1
2
3
4
5
6
7
8
fn main() {
    let x = plus_one(5);
    println!("x is {}", x);
}

fn plus_one(x: i32) -> i32 {
    x + 1
}

其他返回值写法:

1
2
3
fn plus_one(x: i32) -> i32 {
    return x + 1;
}

注释

1
// hello, world

控制流

if
1
2
3
4
5
6
fn main() {
    let num = 3;
    if num != 0 {
        println!("condition was true!");
    }
}
if-else
1
2
3
4
5
6
7
8
fn main() {
    let num = 3;
    if num < 5 {
        println!("condition was true!");
    } else {
        println!("condition was false");
    }
}
if-eles if-else
1
2
3
4
5
6
7
8
9
10
11
12
fn main() {
    let num = 6;
    if num % 4 == 0 {
        println!("num is divisible by 4");
    } else if num % 3 == 0 {
        println!("num is divisible by 3");
    } else if num % 2 == 0 {
        println!("num is divisible by 2");
    } else {
        println!("num is not divisible by 4, 3, or 2");
    }
}
let-if
1
2
3
4
5
6
7
8
9
fn main() {
    let condition = true;
    let num = if condition {
        5
    } else {
        6
    };
    println!("num is {}", num);
}
loop
1
2
3
4
5
fn main() {
    loop { //死循环
        println!("again!");
    }
}
1
2
3
4
5
6
7
8
9
10
fn main() {
    let mut counter = 0;
    let result = loop {
        counter += 1;
        if counter == 10 {
            break counter * 2; //打断 loop
        }
    };
    println!("result is {}", result);
}
while
1
2
3
4
5
6
7
8
fn main() {
    let mut num = 3;
    while num != 0 {
        println!("{}!", num);
        num = num -1;
    }
    println!("LIFTOFF!!!");
}
1
2
3
4
5
6
7
8
9
fn main() {
    let a = [10, 20, 30, 40, 50];
    let mut index = 0;
    while index < 5 {
        println!("the value is {}", a[index]);
        index += 1;
    }
    println!("LIFTOFF!!!");
}
for
1
2
3
4
5
6
7
fn main() {
    let a = [10, 20, 30, 40, 50];
    for element in a.iter() {
        println!("the value is {}", element);
    }
    println!("LIFTOFF!!!");
}
1
2
3
4
5
6
7
8
fn main() {
    //从 1 到数字 4 开始之前
    //rev() 是反转
    for num in (1..4).rev() {
        println!("{}!", num);
    }
    println!("LIFTOFF!!!");
}

猜数字游戏

main.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
use std::io;
use std::cmp::Ordering;
use rand::Rng;

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(1, 101);

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

        io::stdin().read_line(&mut guess)
            .expect("Failed to read line");

        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        println!("You guessed: {}", guess);

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        }
    }
}

cargo.toml

1
2
3
4
5
6
7
8
9
10
[package]
name = "hello"
version = "0.1.0"
authors = ["xvera"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rand = "0.5.5"