Rust系统编程指南

深入理解Rust编程语言,掌握系统级开发技术

Rust编程详解

本文将深入介绍Rust编程语言的核心概念和最佳实践,帮助你掌握系统级开发技术。

所有权系统

  1. 所有权规则
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
fn main() {
    // 所有权转移
    let s1 = String::from("hello");
    let s2 = s1;  // s1的所有权移动到s2
    // println!("{}", s1);  // 编译错误:s1已被移动

    // 克隆
    let s3 = String::from("world");
    let s4 = s3.clone();  // 深拷贝
    println!("s3 = {}, s4 = {}", s3, s4);  // 正常工作
}
  1. 借用规则
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
fn calculate_length(s: &String) -> usize {
    s.len()
}

fn main() {
    let s = String::from("hello");
    let len = calculate_length(&s);
    println!("Length of '{}' is {}", s, len);

    // 可变借用
    let mut s = String::from("hello");
    change(&mut s);
    println!("Changed string: {}", s);
}

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

生命周期

  1. 生命周期标注
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// 显式生命周期
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

// 结构体中的生命周期
struct ImportantExcerpt<'a> {
    part: &'a str,
}

impl<'a> ImportantExcerpt<'a> {
    fn level(&self) -> i32 {
        3
    }
}
  1. 生命周期省略
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// 隐式生命周期
fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();
    
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }
    
    &s[..]
}

并发编程

  1. 线程创建
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }

    handle.join().unwrap();
}
  1. 消息传递
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();
    
    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
    });
    
    let received = rx.recv().unwrap();
    println!("Got: {}", received);
}

错误处理

  1. Result类型
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
use std::fs::File;
use std::io::ErrorKind;

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

    let f = match f {
        Ok(file) => file,
        Err(error) => match error.kind() {
            ErrorKind::NotFound => match File::create("hello.txt") {
                Ok(fc) => fc,
                Err(e) => panic!("Problem creating file: {:?}", e),
            },
            other_error => panic!("Problem opening file: {:?}", other_error),
        },
    };
}
  1. 自定义错误
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#[derive(Debug)]
pub struct AppError {
    pub kind: String,
    pub message: String,
}

impl std::error::Error for AppError {}

impl std::fmt::Display for AppError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}: {}", self.kind, self.message)
    }
}

fn process_data() -> Result<(), AppError> {
    if some_condition {
        return Err(AppError {
            kind: String::from("ValidationError"),
            message: String::from("Invalid input"),
        });
    }
    Ok(())
}

智能指针

  1. Box
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
enum List {
    Cons(i32, Box<List>),
    Nil,
}

use List::{Cons, Nil};

fn main() {
    let list = Cons(1,
        Box::new(Cons(2,
            Box::new(Cons(3,
                Box::new(Nil))))));
}
  1. Rc和Arc
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use std::rc::Rc;

enum List {
    Cons(i32, Rc<List>),
    Nil,
}

use List::{Cons, Nil};

fn main() {
    let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
    let b = Cons(3, Rc::clone(&a));
    let c = Cons(4, Rc::clone(&a));
}

异步编程

  1. async/await
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
use tokio;

#[tokio::main]
async fn main() {
    let handle = tokio::spawn(async {
        // 异步操作
        println!("Hello from task!");
    });

    // 等待任务完成
    handle.await.unwrap();
}

async fn fetch_data(url: &str) -> Result<String, reqwest::Error> {
    let response = reqwest::get(url).await?;
    let body = response.text().await?;
    Ok(body)
}
  1. Future实现
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

struct MyFuture {
    count: u32,
}

impl Future for MyFuture {
    type Output = u32;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if self.count >= 10 {
            Poll::Ready(self.count)
        } else {
            self.count += 1;
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    }
}

最佳实践

  1. 性能优化

    • 使用零成本抽象
    • 避免不必要的克隆
    • 合理使用引用计数
    • 优化内存布局
  2. 开发建议

    • 遵循Rust编码规范
    • 使用cargo工具链
    • 编写单元测试
    • 文档注释

掌握这些Rust编程技巧,将帮助你构建高性能、安全的系统级应用。

使用绝夜之城强力驱动