Rust & OS

· · 学习·文化课

Most of the examples are from The Rust Programming Language.

0 Introduction

hello_world.rs

fn main() {
  println!("Hello World");
}

Function: specify the types of arguments and return value.

fn square(num: i32) -> i32 {
    num * num
}

1 Variable and Primitive Types

  1. Immutable variable
let x = 5;
println!("x has the value {x}");
  1. Specify the type explicitly
let x: i32 = 10;
  1. Mutable variable
let mut x = 3;
x = 5;
  1. Compile time constant
const NUMBER: i32 = 3;
  1. Primitive types

2 Selection and Iteration Structure

If Expression:

let identifier = if animal == "crab" {
        1
    } else if animal == "gopher" {
        2
    } else {
        3
    };

Loops:

fn main() {
    let mut counter = 0;
    let result = loop {
        counter += 1;
        if counter == 10 {
            break counter * 2;
        }
    };
    println!("The result is {result}");
}

Loop labels to disambiguate between multiple loops

'label: loop {
  // ...
  break 'label;
}

while: conditional loops

while number != 0 {
    number -= 1;
}

for: loop through a collection

fn main() {
    let a = [10, 20, 30, 40, 50];
    for element in a {
        println!("the value is: {element}");
    }
}

For: loop with a range

fn main() {
    for number in (1..4).rev() {
        println!("{number}!");
    }
}

3 Ownership and Reference

  1. Mutable and immutable references

    • To avoid data race among multiple references, only one of the following cases are allowed at any time:
      • one mutable reference
      • multiple immutable references
    • Dangling references are detected by the compiler.
      fn main() {
       let s1 = String::from("hello");
       let len = calculate_length(&s1);
       // immutable reference
       println!("The length of '{s1}' is {len}.");
      }
      fn calculate_length(s: &String) -> usize {
       s.len()
      }
      fn main() {
       let mut s = String::from("hello");
       change(&mut s); // mutable reference
      }
      fn change(some_string: &mut String) {
       some_string.push_str(", world");
      }
  2. Slice is a reference to a continuous part of a collection.

    • String Slice &str: &s[l..r]. Both l and r can be omitted if started or ended at the endpoint.
    • String literals are as slices. For example, in the statement let s = "Hello", s is a &str type.

4 Struct

5 Enums and Pattern Matching

Enumerations (Enums) allow you define a type by enumerating all its possible variants.

  1. Define and use an enum.
    
    enum IpAddrKind {
     V4,
     V6,
    }

let four = IpAddrKind::V4; let six = IpAddrKind::V6;


2. You can put data directly into each enum variant.

```rust
enum IpAddr {
    V4(String),
    V6(String),
}

let home = IpAddr::V4(String::from("127.0.0.1"));
let loopback = IpAddr::V6(String::from("::1"));
  1. Each variant can have different types and amounts of associated data.
enum IpAddr {
    V4(u8, u8, u8, u8),
    V6(String),
}

let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from("::1"));
  1. The Option enum: it has advantages over null values.
    enum Option<T> {
       None,
       Some(T),
    }

let absent_number: Option<i32> = None;


5. The `match` control flow construct

- `match` keyword followed by an expression, then match arms. Each arm has two parts: a pattern and some code.
- It compares the expression with each pattern **in order**.
- The comma following the arm is optional if you use curly brackets `=> {..}`.

```rust
enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter => 25,
    }
}

let five = Some(5); let six = plus_one(five); let none = plus_one(None);


- `match` must be **exhaustive** (cover all possible cases).
- `_` is a special pattern when we want a **catch-all** but don't want to *use* the value.
- `if let` , a "syntax sugar"
```rust
let mut count = 0;
match coin {
    Coin::Quarter(state) => println!("State quarter from {state:?}!"),
    _ => count += 1,
}
// Equal to
let mut count = 0;
if let Coin::Quarter(state) = coin {
    println!("State quarter from {state:?}!");
} else {
    count += 1;
}

6 Packages, Crates and Modules

7 Common Collections

  1. Vectors
  1. String. String is implemented as a wrapper around a vector of bytes with some extra guarantees, restrictions and capabilities.

    • Basic operations:
      
      let mut s = String::new(); // create an empty String
      s.push('C'); // push like a vector

let mut s1 = String::from("foo"); let s2 = "bar"; s1.push_str(s2); // will not take the ownership of s2, // and the content of s2 will be copied

  - Add operation: the first operand will be moved, and the second operand should be a `&str`.
  ```rust
  fn main() {
      let mut s1 = String::from("Hello");
      let s2 = String::from("World");
      let s3 = s1 + &s2;
      // s1 moved to s3
      println!("s3 = {s3}");
  }

let s = format!("{s1}-{s2}-{s3}"); // all are copies

  - Iterate: `.char()` or `.bytes()`
```rust
for c in "Зд".chars() {
    println!("{c}");
} // З д
for b in "Зд".bytes() {
    println!("{b}");
} // 208 151 208 180