开发
软件开发相关知识
Rust语言圣经2.0:从入门到企业级系统开发
一、Rust概述
1.1 Rust优势
内存安全:无需GC
零成本抽象:高性能
并发安全:防止数据竞争
现代工具链:Cargo、Clippy
1.2 适合场景
操作系统
WebAssembly
网络服务
嵌入式
二、所有权系统
2.1 三大规则
// 1. 每个值有且只有一个所有者
// 2. 当所有者离开作用域,值被释放
// 3. 可以有多个不可变引用或一个可变引用
fn main() {
let s1 = String::from("hello");
let s2 = s1; // s1被移动到s2
println!("{}", s2);
}2.2 引用与借用
fn calculate_length(s: &String) -> usize {
s.len()
}
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("{}的长度是{}", s1, len);
}三、生命周期
3.1 生命周期标注
fn longest(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}四、并发编程
4.1 线程
use std::thread;
fn main() {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("子线程: {}", i);
}
});
handle.join().unwrap();
}4.2 消息传递
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send(String::from("消息")).unwrap();
});
println!("收到: {}", rx.recv().unwrap());
}五、WebAssembly
5.1 wasm-bindgen
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}六、总结
Rust核心要点:
1. 所有权:无GC的内存安全
2. 生命周期:引用的有效性保证
3. trait:接口抽象
4. 并发:安全的多线程