Skip to content

Rust lang

String

let s = "hello";

let s = String::from("hello");

String vs "abc" vs str

&str is &s[..] string slice. String is string object. ".." is string literal.

Key Concepts

Ownership, Reference, borrowing, pattern matching, Stack and Heap, Result and Panic, Traits, Lifetimes, smart pointers

Move

    let x = 5;
    let y = x;

    let s1 = String::from("hello");
    let s2 = s1;
fn takes_and_gives_back(a_string: String) -> String { // a_string comes into
    a_string  // a_string is returned and moves out to the calling function
}

Reference/borrowing

fn main() {
    let s1 = String::from("hello");

    let len = calculate_length(&s1);

    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);
}

fn change(some_string: &mut String) {
    some_string.push_str(", world");
}

slice Reference

    let s = String::from("hello world");

    let hello = &s[0..5];
    let world = &s[6..11];

Slice ref type, &[i32]

enum

    enum IpAddrKind {
        V4,
        V6,
    }

    struct IpAddr {
        kind: IpAddrKind,
        address: String,
    }

    let home = IpAddr {
        kind: IpAddrKind::V4,
        address: String::from("127.0.0.1"),
    };

    let loopback = IpAddr {
        kind: IpAddrKind::V6,
        address: String::from("::1"),
    };

match

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,
    }
}
fn main(){
    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);
}
    let mut count = 0;
    if let Coin::Quarter(state) = coin {
        println!("State quarter from {state:?}!");
    } else {
        count += 1;
    }

Result

use std::fs::File;

fn main() {
    let greeting_file_result = File::open("hello.txt");

    let greeting_file = match greeting_file_result {
        Ok(file) => file,
        Err(error) => panic!("Problem opening the file: {error:?}"),
    };
}

return result error directly

use std::fs::File;
use std::io::{self, Read};

fn read_username_from_file() -> Result<String, io::Error> {
    let mut username_file = File::open("hello.txt")?;
    let mut username = String::new();
    username_file.read_to_string(&mut username)?;
    Ok(username)
}

Other Core Concepts

Generics, enum, Closures, Iterators, struct, threading, oop

struct

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    println!(
        "The area of the rectangle is {} square pixels.",
        rect1.area()
    );
}

Rust 语言核心 (Core Rust)

所有权系统: Ownership, Borrowing (不可变与可变借用), Lifetimes (生命周期标注)。

类型系统: Trait (接口设计)、泛型、关联类型、Orphan Rule。

错误处理: Result 与 Option 模式、Panic 机制、自定义 Error 类型。

智能指针: Box, Rc, Arc, RefCell, Cell。

模式匹配: Match 语法、If let、枚举 (Enum) 的代数数据类型应用。

并发与异步 (Concurrency & Async)

无畏并发: Send 与 Sync Trait、互斥锁 (Mutex)、读写锁 (RwLock)。

通道通信: MPSC (多生产者单消费者)、SPSC (无锁队列应用)。

异步编程: async/await 原理、Future Trait、Tokio/async-std 运行时。

多线程: Rayon 并行计算库、线程池设计。

底层性能与集成 (Low-level & Interop)

Unsafe Rust: 裸指针操作、内存对齐、FFI (与 C/C++ 库交互)。

内存布局: #[repr(C)]、#[repr(packed)]、Zero-cost Abstractions (零成本抽象)。

内联汇编: asm! 宏在极低延迟场景的应用。

宏系统: Declarative Macros (macro_rules!)、Derive 宏、过程宏 (Procedural Macros)。

量化特定生态 (Quant Ecosystem)

数值计算: ndarray (类似 NumPy)、nalgebra (线性代数)、polars (高性能 DataFrame)。

序列化: Serde 框架 (处理 JSON/MessagePack/Binary 极速转换)。

定点数与精度: rust_decimal、fixed 库(避免浮点数在交易中的误差)。

时间处理: chrono 与 time 库的高精度处理。

工程化与架构 (Engineering)

包管理: Cargo 工作空间 (Workspaces)、特性开关 (Features)、构建脚本 (build.rs)。

测试: 单元测试、集成测试、基准测试 (Criterion)。

静态分析: Clippy 优化建议、Rust-analyzer 性能分析。