名称: rust 描述: 使用所有权、生命周期和特质编写地道的Rust代码。用于Rust开发、内存安全或系统编程。
Rust开发
编写安全、高性能的Rust代码。
使用时机
- 编写Rust代码
- 所有权和生命周期问题
- 特质实现
- 异步Rust
- FFI和不安全代码
所有权模式
借用
// 不可变借用
fn print_length(s: &str) {
println!("Length: {}", s.len());
}
// 可变借用
fn append_greeting(s: &mut String) {
s.push_str(", world!");
}
// 所有权转移
fn consume(s: String) -> String {
format!("Consumed: {}", s)
}
生命周期
// 显式生命周期注解
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
// 带生命周期的结构体
struct Parser<'a> {
input: &'a str,
position: usize,
}
错误处理
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Parse error at line {line}")]
Parse { line: usize },
#[error("Not found: {0}")]
NotFound(String),
}
// 使用Result
fn read_config(path: &Path) -> Result<Config, AppError> {
let content = std::fs::read_to_string(path)?;
parse_config(&content).map_err(|e| AppError::Parse { line: e.line })
}
特质
// 定义特质
trait Summary {
fn summarize(&self) -> String;
// 默认实现
fn preview(&self) -> String {
format!("{}...", &self.summarize()[..50])
}
}
// 为类型实现
impl Summary for Article {
fn summarize(&self) -> String {
format!("{} by {}", self.title, self.author)
}
}
// 带特质界限的泛型
fn notify<T: Summary + Display>(item: &T) {
println!("Breaking: {}", item.summarize());
}
异步
use tokio;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let response = fetch_data().await?;
process(response).await
}
async fn fetch_data() -> Result<Data, Error> {
let client = reqwest::Client::new();
let resp = client.get(URL).send().await?.json().await?;
Ok(resp)
}
测试
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_valid() {
let result = parse("valid input");
assert!(result.is_ok());
assert_eq!(result.unwrap(), expected);
}
#[test]
#[should_panic(expected = "empty input")]
fn test_parse_empty() {
parse("");
}
}
示例
输入: “Fix lifetime error” 操作: 分析借用检查器消息,调整生命周期或所有权
输入: “Make this async” 操作: 添加async/await,使用tokio运行时,处理异步错误