跳到正文

学习·文化课

Rust & OS

hongzy约 24 分钟
原文
文章信息与版本

文章信息

发布
2024年11月21日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 24 分钟
获赞
2

版本

  1. v1当前

Most of the examples are from The Rust Programming Language.

0 Introduction

hello_world.rs

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

Function: specify the types of arguments and return value.

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

1 Variable and Primitive Types

  1. Immutable variable
Rust
let x = 5;
println!("x has the value {x}");
  1. Specify the type explicitly
Rust
let x: i32 = 10;
  1. Mutable variable
Rust
let mut x = 3;
x = 5;
  1. Compile time constant
Rust
const NUMBER: i32 = 3;
  1. Primitive types
  • Integer
    • Types:i/u + 8/16/32/64/128 and isize, usize
    • Literals
      • Decimal 98_222
      • Hex 0xff
      • Octal 0o77
      • Binary 0b1111_0000
      • Byte (u8, ASCII) b'A'
    • Overflow
      • Panic in the debug mode
      • Two’s complement wrapping (e.g. 255+1→0255 + 1 \to 0 for u8) in the release mode
  • Char: 4 bytes, Unicode.
  • Tuple:
    • Create
    • Destructure
    • Access one particular element via period .
    • The tuple without any values is called a unit (). It represents an empty return type or value. Expressions without an explicit return statement return a unit.
    Rust
    let tup: (i32, f64, u8) = (500, 6.4, 1);
    let (x, y, z) = tup;
    let y2 = tup.1;
  • Array
    • Initialize with a comma-separated list inside square bracket.
    • Initialize with an initial value and a length, separated by a semicolon.
    • Index out of bounds will trigger a runtime error.
    Rust
    let a = [1, 1, 1, 1, 1];
    let b = [1; 5];

2 Selection and Iteration Structure

If Expression:

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

Loops:

Rust
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

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

while: conditional loops

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

for: loop through a collection

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

For: loop with a range

Rust
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.
Rust
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()
}
Rust
fn main() {
    let mut s = String::from("hello");
    change(&mut s); // mutable reference
}
fn change(some_string: &mut String) {
    some_string.push_str(", world");
}
  1. 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

  • Define a struct

    • A struct name describes the significance of the pieces of data grouped together.
    • Inside the curly brackets, we defined the types and names of the pieces of data, which we called fields.
    Rust
    struct User {
      active: bool,
      username: String,
      email: String,
      sign_in_count: u64,
    }
  • We create an instance by stating the name of the struct and then add curly brackets containing key-value pairs.

    Rust
    fn main() {
        let user1 = User {
            active: true,
            username: String::from("someusername123"),
            email: String::from("someone@example.com"),
            sign_in_count: 1,
        };
    }
  • Field Init Shorthand. If the field we are initializing has the same name as the variable that we assign to it, the duplicate name: name can be replaced by simply a name.

  • It is not allowed to mark some fields as mutable. mut can only be specified when creating the instance.

  • Creating instances from other instances with struct update syntax.

    Rust
    let user2 = User {
        email: String::from("another@example.com"),
        ..user1 // other fields same as user1
    };
  • Tuple structs are used when you want to add meanings to tuples.

    Rust
    struct Color(i32, i32, i32);
    struct Point(i32, i32, i32);
    
    fn main() {
        let black = Color(0, 0, 0);
        let origin = Point(0, 0, 0);
    }
  • Unit-like structs are useful when you need to implement a trait but don’t want to store any data in the type itself.

    Rust
    struct AlwaysEqual;
    fn main() {
        let subject = AlwaysEqual;
    }
  • If a field is not owned by the struct, you must use a lifetime specifier. More about this in later sections.

  • Derive traits.

    • If you want to print a structure, you can use {:?} or {:#?} (for pretty-print). But you have to derive the debug trait first #[derive(Debug)].
    Rust
    #[derive(Debug)]
    struct Rectangle {
        width: u32,
        height: u32,
    }
    fn main() {
        let rect1 = Rectangle {
            width: 30,
            height: 50,
        };
        println!("rect1 is {rect1:?}");
    }
    • Another way is to use dbg! macro. The difference is it will takes the ownership of the expression, print the message to the stderr, and return the expression.
    Rust
    #[derive(Debug)]
    struct Rectangle {
        width: u32,
        height: u32,
    }
    
    fn main() {
        let scale = 2;
        let rect1 = Rectangle {
            width: dbg!(30 * scale),
            height: 50,
        };
    
        dbg!(&rect1);
    }

    The output looks like this:

    代码
    [src/main.rs:10:16] 30 * scale = 60
    [src/main.rs:14:5] &rect1 = Rectangle {
        width: 60,
        height: 50,
    }
  • Methods of a structure.

    Rust
    struct Rectangle {
      width: u32,
      height: u32,
    }
    
    impl Rectangle {
      fn area(&self) -> u32 {
        self.width * self.height
      }
    }
    • Automatic referencing and dereferencing. Rust doesn’t have an equivalent to -> in C/C++; instead, it automatically adds in &, &mut or * so object matches the signature of the method. It works since methods specify the type of self, as reading &self, mutating &mut self, or consuming self.

    • We can define associated functions (functions in the impl) that don’t have self as their first parameter (thus they are not methods).

    Rust
    impl Rectangle {
      fn square(size: u32) -> Self {
        Self {
          width: size,
          height: size,
        }
      }
    }
    // in main:
    let sq = Rectangle::square(3);  

5 Enums and Pattern Matching

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

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

let four = IpAddrKind::V4;
let six = IpAddrKind::V6;
  1. 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.
Rust
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.
Rust
enum Option<T> {
    None,
    Some(T),
}
  • It is so useful that it is included in the prelude (rust’s standard library that is implicitly imported into every Rust program).
  • Its variants are also in the prelude, so you can use Some and None directly.
  • For the example below, you must specify a type for None.
Rust
let some_number = Some(5); // Option<i32>
let some_char = Some('e'); // Option<char>

let absent_number: Option<i32> = None;
  1. 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,
    }
}
  • Pattern that bind to values:
Rust
#[derive(Debug)] // so we can inspect the state in a minute
enum UsState {
    Alabama,
    Alaska,
    // --snip--
}
enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(UsState),
}
fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter(state) => {
            println!("State quarter from {state:?}!");
            25
        }
    }
}
  • An example of matching with Option<T>
Rust
fn plus_one(x: Option<i32>) -> Option<i32> {
    match x {
        None => None,
        Some(i) => Some(i + 1),
    }
}

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
  • Create
Rust
let v: Vec<i32> = Vec::new();
let v = vec![1, 2, 3];
  • Update
Rust
let mut v = Vec::new();
v.push(5);
  • Read an element: it’s better to use .get to avoid out of bounds.
Rust
let v2: i32 = &v[2]; // panic if out of bound
let third: Option<&i32> = v.get(2);
  • Iterate
Rust
let v = vec![1, 2, 3];
for i in &v {
  println!("{i}");
}
let mut v = vec![1, 2, 3];
for i in &mut v {
  *i += 10; // deferencing
}
  1. String. String is implemented as a wrapper around a vector of bytes with some extra guarantees, restrictions and capabilities.

    • Basic operations:
Rust
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}");
}
  • format! macro: a convenient way to create a new string
Rust
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");

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
原文