SOC 직업 분류 기준
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
직접 명령은 검토 Prompt를 거치지 않습니다. 실행하기 전에 소스를 확인하세요.
npx skills add https://github.com/microwind/ai-skills --skill rust명령은 한 줄로 유지됩니다. 복사하기 전에 가로로 스크롤해 전체 내용을 확인하세요.
로컬 사본을 원하시나요? SkillsMP에서 현재 제공할 수 있는 파일을 다운로드하세요.
SKILL.md 표시 중
| name | Rust系统编程 |
| description | 当进行Rust系统编程时,分析内存管理,优化并发性能,解决安全问题。验证系统架构,设计高性能应用,和最佳实践。 |
| license | MIT |
Rust是一门系统编程语言,以其内存安全、并发安全和高性能而著称。Rust通过所有权系统、借用检查器和生命周期机制,在编译时就能防止许多常见的编程错误。不当的Rust编程会导致编译错误、性能问题、代码复杂。
核心原则: 好的Rust代码应该内存安全、并发安全、性能优良、可读性强。坏的Rust代码会滥用unsafe、性能损耗、难以维护。
始终:
触发短语:
问题: 借用检查器错误
原因: 不理解Rust的借用规则
解决: 学习所有权和借用机制,使用引用和克隆
问题: 生命周期错误
原因: 生命周期标注不正确
解决: 理解生命周期规则,使用生命周期标注
问题: 过度克隆导致性能下降
原因: 不理解所有权转移
解决: 合理使用引用,避免不必要的克隆
问题: 频繁的内存分配
原因: 不了解Rust的内存管理
解决: 使用栈分配、对象池等技术
问题: 数据竞争
原因: 不正确的共享数据访问
解决: 使用Rust的并发安全机制
问题: 死锁
原因: 锁的获取顺序不当
解决: 遵循一致的锁获取顺序
// 基础所有权概念
fn ownership_basics() {
// 字符串所有权转移
let s1 = String::from("Hello");
let s2 = s1; // 所有权从 s1 转移到 s2
// println!("{}", s1); // 编译错误:s1 不再拥有字符串
println!("{}", s2); // 正确:s2 拥有字符串
// 克隆避免所有权转移
let s3 = String::from("World");
let s4 = s3.clone(); // 克隆数据,s3 仍然有效
println!("{}, {}", s3, s4); // 正确:两个都有效
// 函数参数的所有权转移
let s5 = String::from("Rust");
takes_ownership(s5); // s5 的所有权转移到函数
// println!("{}", s5); // 编译错误:s5 不再有效
let s6 = String::from("Programming");
let len = calculate_length(&s6); // 借用,不转移所有权
println!("'{}' 的长度是 {}", s6, len); // s6 仍然有效
}
(some_string: ) {
(, some_string);
}
(s: &) {
s.()
}
() {
= ::();
= &s;
= &s;
(, r1, r2);
= & s;
r3.();
(, r3);
}
() {
= ::();
= &s[..];
= &s[..];
(, hello, world);
= [, , , , ];
= &a[..];
(, slice);
= (&s);
(, word);
}
(s: &) & {
= s.();
(i, &item) bytes.().() {
item == {
&s[..i];
}
}
&s[..]
}
// 结构体定义
#[derive(Debug, Clone, Copy)]
struct Point {
x: f64,
y: f64,
}
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
top_left: Point,
}
impl Rectangle {
// 关联函数(静态方法)
fn new(width: u32, height: u32) -> Self {
Rectangle {
width,
height,
top_left: Point { x: 0.0, y: 0.0 },
}
}
// 方法
fn area(&self) -> u32 {
self.width * self.height
}
// 可变方法
fn resize(&mut self, new_width: u32, new_height: u32) {
self.width = new_width;
self.height = new_height;
}
// 获取所有权的方法
fn move_to(self, new_x: f64, new_y: f64) -> Self {
Rectangle {
width: self.width,
height: self.height,
top_left: Point { x: new_x, y: new_y },
}
}
}
{
(, , , ),
(),
}
{
Quit,
Move { x: , y: },
(),
(, , ),
}
{
(&) {
{
Message::Quit => (),
Message::Move { x, y } => (, x, y),
Message::(text) => (, text),
Message::(r, g, b) => (, r, g, b),
}
}
}
() {
= [, , , , ];
= numbers.().(|&&x| x % == );
first_even {
(num) => (, num),
=> (),
}
= first_even.(|x| x * );
(, doubled);
= doubled.();
(, value);
}
() <, > {
= ;
= ;
y == {
(.())
} {
(x / y)
}
}
() {
() {
(result) => (, result),
(error) => (, error),
}
= (, );
(, result);
= (, );
(, result);
}
(x: , y: ) <, > {
y == {
(.())
} {
(x / y)
}
}
use std::fs;
use std::io::{self, Read};
// 自定义错误类型
#[derive(Debug)]
enum AppError {
Io(io::Error),
ParseError(std::num::ParseIntError),
Custom(String),
}
impl std::fmt::Display for AppError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
AppError::Io(err) => write!(f, "IO错误: {}", err),
AppError::ParseError(err) => write!(f, "解析错误: {}", err),
AppError::Custom(msg) => write!(f, "自定义错误: {}", msg),
}
}
}
impl std::error::Error for AppError {}
// From trait 实现
impl From<io::Error> for AppError {
fn from(err: io::Error) -> Self {
AppError::Io(err)
}
}
impl From<std::num::ParseIntError> {
(err: std::num::ParseIntError) {
AppError::(err)
}
}
(path: &) <, AppError> {
= ::();
= fs::File::(path)?;
file.(& content)?;
(content)
}
(content: &) <<>, AppError> {
content
.()
.(|line| line.().parse::<>())
.()
}
(path: &) <, AppError> {
= (path)?;
= (&content)?;
(numbers.().())
}
(x: , y: ) <> {
y == {
} {
(x / y)
}
}
() {
= [
(, ),
(, ),
(, ),
];
(x, y) operations {
(x, y) {
(result) => (, x, y, result),
=> (, x, y),
}
}
}
std::error;
std::fmt;
{
message: ,
source: << error::Error + + >>,
}
::Display {
(&, f: & fmt::Formatter) fmt:: {
(f, , .message)
}
}
::Error {
(&) <&( error::Error + )> {
.source.().(|e| e.())
}
}
() <(), DatabaseError> {
(DatabaseError {
message: .(),
source: (::(io::Error::(io::ErrorKind::ConnectionRefused, ))),
})
}
use std::thread;
use std::sync::{Arc, Mutex, Condvar};
use std::sync::mpsc;
use std::time::Duration;
// 基础线程使用
fn basic_threading() {
let handle = thread::spawn(|| {
for i in 1..=5 {
println!("线程中的数字: {}", i);
thread::sleep(Duration::from_millis(100));
}
});
for i in 1..=3 {
println!("主线程中的数字: {}", i);
thread::sleep(Duration::from_millis(100));
}
handle.join().unwrap();
}
// 通道通信
fn channel_communication() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let vals = vec![
String::from("你好"),
String::from("来自"),
::(),
];
vals {
tx.(val).();
thread::(Duration::());
}
});
rx {
(, received);
}
}
() {
(tx, rx) = mpsc::();
.. {
= tx.();
thread::( || {
.. {
= (, i, j);
tx_clone.(message).();
thread::(Duration::());
}
});
}
(tx);
rx {
(, received);
}
}
() {
= Arc::(Mutex::());
= [];
.. {
= Arc::(&counter);
= thread::( || {
.. {
= counter_clone.().();
*num += ;
}
});
handles.(handle);
}
handles {
handle.().();
}
(, *counter.().());
}
() {
= Arc::((Mutex::(), Condvar::()));
= Arc::(&pair);
thread::( || {
( lock, cvar) = *pair_clone;
= lock.().();
*started = ;
();
cvar.();
});
( lock, cvar) = *pair;
= lock.().();
!*started {
started = cvar.(started).();
}
();
}
std::sync::atomic::{AtomicUsize, Ordering};
() {
= AtomicUsize::();
= [];
.. {
= counter.();
= thread::( || {
.. {
counter_clone.(, Ordering::SeqCst);
}
});
handles.(handle);
}
handles {
handle.().();
}
(, counter.(Ordering::SeqCst));
}
use tokio;
use tokio::time::{sleep, Duration};
use futures::future::join_all;
// 基础异步函数
async fn say_hello() {
println!("Hello");
sleep(Duration::from_millis(100)).await;
println!("World");
}
// 异步函数返回值
async fn calculate_sum(a: i32, b: i32) -> i32 {
sleep(Duration::from_millis(50)).await;
a + b
}
// 异步迭代
async fn process_numbers() {
let numbers = vec![1, 2, 3, 4, 5];
for num in numbers {
let result = async_process(num).await;
println!("处理结果: {}", result);
}
}
async fn async_process(num: i32) {
(Duration::()).;
num *
}
() {
= (, );
= (, );
= (, );
(result1, result2, result3) = tokio::join!(task1, task2, task3);
(, result1, result2, result3);
}
(id: , delay_ms: ) {
(Duration::(delay_ms)).;
(, id)
}
() {
: <_> = (..=)
.(|i| (i, i * ))
.();
= (tasks).;
results {
(, result);
}
}
(success: ) <, > {
(Duration::()).;
success {
(.())
} {
(.())
}
}
() {
(). {
(result) => (, result),
(error) => (, error),
}
= ().;
(, result);
}
() <, > {
= ().?;
((, result))
}
futures::stream::{, StreamExt};
() {
= stream::(..=);
= numbers
.(|n| {
(Duration::()).;
n *
})
.();
processed.for_each(|result| {
(, result);
}).;
}
tokio::sync::mpsc;
() {
(tx, rx) = mpsc::();
tokio::( {
..= {
= (, i);
tx.(message)..();
(Duration::()).;
}
});
(message) = rx.(). {
(, message);
}
}
() {
().;
= (, ).;
(, sum);
().;
().;
().;
().;
().;
().;
}
use std::rc::Rc;
use std::cell::RefCell;
use std::sync::{Arc, Mutex};
// Box<T> - 堆分配
fn box_example() {
let b = Box::new(5);
println!("b = {}", b);
// 递归类型需要 Box
#[derive(Debug)]
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
println!("{:?}", list);
}
// Rc<T> - 引用计数
fn rc_example() {
#[derive(Debug)]
struct Node {
value: i32,
children: RefCell<Vec<Rc<Node>>>,
}
let leaf = Rc::new(Node {
value: 3,
children: RefCell::new([]),
});
{
= Rc::(Node {
value: ,
children: RefCell::([Rc::(&leaf)]),
});
leaf.children.().(Rc::(&branch));
}
(, Rc::(&leaf));
}
() {
= Arc::(Mutex::());
= [];
.. {
= Arc::(&counter);
= thread::( || {
.. {
= counter_clone.().();
*num += ;
}
});
handles.(handle);
}
handles {
handle.().();
}
(, *counter.().());
}
<T>(T);
<T> MyBox<T> {
(x: T) MyBox<T> {
(x)
}
}
<T> std::ops::Deref <T> {
= T;
(&) &::Target {
&.
}
}
() {
= ;
= MyBox::(x);
(, x);
(, *y);
(, *(y.()));
}
{
data: ,
}
{
(& ) {
(, .data);
}
}
() {
= CustomSmartPointer {
data: ::(),
};
= CustomSmartPointer {
data: ::(),
};
();
}