| name | rust-reference |
| description | Rust 语言参考技能。提供 Rust 语言的完整参考,包括语法、类型系统、内存模型、并发模型等。TRIGGER when: 用户需要了解 Rust 语言细节、查阅语言规范、或需要深入了解 Rust 内部机制时触发。SKIP: 基础 Rust 开发。 |
Rust 语言参考技能
本技能提供 Rust 语言的完整参考,基于 Rust Reference。
触发条件
当用户执行以下操作时触发此技能:
- 了解 Rust 语言细节
- 查阅语言规范
- 深入了解 Rust 内部机制
跳过条件
以下情况不触发此技能:
- 基础 Rust 开发(使用
rust-language 技能)
语法
关键字
as, async, await, break, const, continue, crate, dyn, else, enum, extern
false, fn, for, if, impl, in, let, loop, match, mod, move, mut, pub, ref
return, self, Self, static, struct, super, trait, true, type, unsafe, use
where, while, yield
abstract, become, box, do, final, macro, override, priv, try, typeof
unsized, virtual
运算符
+ - * / %
== != < > <= >=
! && ||
& | ^ ! << >>
= += -= *= /= %= &= |= ^= <<= >>=
.. ..=
?
->
=>
@
#
$
类型系统
原始类型
bool
char
i8, i16, i32, i64, i128, isize
u8, u16, u32, u64, u128, usize
f32, f64
()
!
复合类型
(i32, f64, bool)
()
(T,)
[i32; 5]
[T; N]
[T]
str
类型别名
type Kilometers = i32;
type Thunk = Box<dyn Fn() + Send + 'static>;
type Result<T> = std::result::Result<T, std::io::Error>;
内存模型
所有权
let s1 = String::from("hello");
let s2 = s1;
{
let s = String::from("hello");
}
引用
let s = String::from("hello");
let r = &s;
let mut s = String::from("hello");
let r = &mut s;
生命周期
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
并发模型
线程
use std::thread;
let handle = thread::spawn(|| {
});
handle.join().unwrap();
let (tx, rx) = mpsc::channel();
同步原语
use std::sync::{Mutex, RwLock, Arc};
let m = Mutex::new(5);
{
let mut num = m.lock().unwrap();
*num = 6;
}
let lock = RwLock::new(5);
let r1 = lock.read().unwrap();
let r2 = lock.read().unwrap();
let mut w = lock.write().unwrap();
let counter = Arc::new(Mutex::new(0));
let counter_clone = Arc::clone(&counter);
Send 和 Sync
unsafe impl Send for MyType {}
unsafe impl Sync for MyType {}
模式匹配
模式语法
42
"hello"
true
let x = 5;
let (x, y) = (1, 2);
let _ = 5;
let (_, y) = (1, 2);
let &x = &5;
let ref x = 5;
struct Point { x: i32, y: i32 }
let Point { x, y } = Point { x: 1, y: 2 };
let Point { x, .. } = Point { x: 1, y: 2 };
enum Shape { Circle(f64), Rectangle(f64, f64) }
let Shape::Circle(radius) = shape;
let Shape::Rectangle(width, height) = shape;
1..=5
'a'..='z'
match x {
n if n > 0 => println!("正数"),
n if n < 0 => println!("负数"),
_ => println!("零"),
}
match x {
n @ 1..=5 => println!("1 到 5: {}", n),
_ => println!("其他"),
}
属性
内置属性
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Point { x: i32, y: i32 }
#[cfg(target_os = "linux")]
fn linux_only() {}
#[test]
fn test_function() {}
#[test]
#[ignore]
fn expensive_test() {}
#[test]
#[should_panic(expected = "除以零")]
fn test_panic() {}
#[doc = "这是文档属性"]
fn documented() {}
自定义属性
#[my_attribute]
fn decorated() {}
#[derive(MyMacro)]
struct MyStruct;
宏
声明宏
macro_rules! my_macro {
() => {
println!("无参数");
};
($x:expr) => {
println!("一个参数: {}", $x);
};
($x:expr, $y:expr) => {
println!("两个参数: {} 和 {}", $x, $y);
};
}
fn main() {
my_macro!();
my_macro!(42);
my_macro!(1, 2);
}
过程宏
#[proc_macro_derive(MyMacro)]
pub fn my_macro_derive(input: TokenStream) -> TokenStream {
}
#[proc_macro_attribute]
pub fn my_attribute(args: TokenStream, input: TokenStream) -> TokenStream {
}
#[proc_macro]
pub fn my_macro(input: TokenStream) -> TokenStream {
}
最佳实践
- 理解所有权:所有权是 Rust 的核心概念
- 使用引用:避免不必要的所有权转移
- 生命周期标注:让编译器推断,只在必要时标注
- 模式匹配:使用 match 和 if let 处理枚举
- 属性驱动:使用属性简化代码
常见陷阱
- 借用检查器:理解可变和不可变借用的规则
- 生命周期:理解引用的有效期
- 类型推断:有时需要显式类型标注
- 模式匹配:确保覆盖所有情况
- 宏卫生:理解宏的作用域和展开规则