| name | rust-patterns |
| description | 안전하고 성능이 뛰어난 애플리케이션 구축을 위한 관용적인 러스트 패턴, 소유권, 에러 처리, 트레이트, 동시성 및 모범 사례입니다. |
| origin | ECC |
러스트 개발 패턴 (Rust Development Patterns)
안전하고 성능이 뛰어나며 유지보수가 쉬운 애플리케이션을 구축하기 위한 관용적인(idiomatic) 러스트 패턴과 모범 사례입니다.
사용 시점
- 새로운 러스트 코드를 작성할 때
- 러스트 코드를 리뷰할 때
- 기존 러스트 코드를 리팩터링할 때
- 크레이트(crate) 구조 및 모듈 레이아웃을 설계할 때
동작 방식
이 스킬은 6가지 핵심 영역에서 관용적인 러스트 컨벤션을 적용합니다: 컴파일 타임에 데이터 경합을 방지하는 소유권 및 빌림(ownership and borrowing), 라이브러리용 thiserror 및 애플리케이션용 anyhow를 사용한 Result/? 에러 전파, 유효하지 않은 상태를 표현 불가능하게 만드는 열거형(enums) 및 철저한 패턴 매칭, 제로 비용 추상화를 위한 트레이트(traits) 및 제네릭, Arc<Mutex<T>>, 채널, async/await를 통한 안전한 동시성, 그리고 도메인별로 조직화된 최소한의 pub 노출입니다.
핵심 원칙
1. 소유권 및 빌림 (Ownership and Borrowing)
러스트의 소유권 시스템은 컴파일 타임에 데이터 경합과 메모리 버그를 방지합니다.
fn process(data: &[u8]) -> usize {
data.len()
}
fn store(data: Vec<u8>) -> Record {
Record { payload: data }
}
fn process_bad(data: &Vec<u8>) -> usize {
let cloned = data.clone();
cloned.len()
}
유연한 소유권을 위해 Cow 사용
use std::borrow::Cow;
fn normalize(input: &str) -> Cow<'_, str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_"))
} else {
Cow::Borrowed(input)
}
}
에러 처리 (Error Handling)
Result와 ? 사용 — 프로덕션에서 unwrap() 금지
use anyhow::{Context, Result};
fn load_config(path: &str) -> Result<Config> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("failed to read config from {path}"))?;
let config: Config = toml::from_str(&content)
.with_context(|| format!("failed to parse config from {path}"))?;
Ok(config)
}
fn load_config_bad(path: &str) -> Config {
let content = std::fs::read_to_string(path).unwrap();
toml::from_str(&content).unwrap()
}
라이브러리는 thiserror, 애플리케이션은 anyhow 사용
use thiserror::Error;
#[derive(Debug, Error)]
pub enum StorageError {
#[error("record not found: {id}")]
NotFound { id: String },
#[error("connection failed")]
Connection(#[from] std::io::Error),
#[error("invalid data: {0}")]
InvalidData(String),
}
use anyhow::{bail, Result};
fn run() -> Result<()> {
let config = load_config("app.toml")?;
if config.workers == 0 {
bail!("worker count must be > 0");
}
Ok(())
}
중첩 매칭 대신 Option 컴비네이터 사용
fn find_user_email(users: &[User], id: u64) -> Option<String> {
users.iter()
.find(|u| u.id == id)
.map(|u| u.email.clone())
}
fn find_user_email_bad(users: &[User], id: u64) -> Option<String> {
match users.iter().find(|u| u.id == id) {
Some(user) => match &user.email {
email => Some(email.clone()),
},
None => None,
}
}
열거형(Enums) 및 패턴 매칭
상태를 열거형으로 모델링
enum ConnectionState {
Disconnected,
Connecting { attempt: u32 },
Connected { session_id: String },
Failed { reason: String, retries: u32 },
}
fn handle(state: &ConnectionState) {
match state {
ConnectionState::Disconnected => connect(),
ConnectionState::Connecting { attempt } if *attempt > 3 => abort(),
ConnectionState::Connecting { .. } => wait(),
ConnectionState::Connected { session_id } => use_session(session_id),
ConnectionState::Failed { retries, .. } if *retries < 5 => retry(),
ConnectionState::Failed { reason, .. } => log_failure(reason),
}
}
철저한 매칭 — 비즈니스 로직에 와일드카드 금지
match command {
Command::Start => start_service(),
Command::Stop => stop_service(),
Command::Restart => restart_service(),
}
match command {
Command::Start => start_service(),
_ => {}
}
트레이트(Traits) 및 제네릭(Generics)
제네릭으로 받고, 구체적인 타입으로 반환
fn read_all(reader: &mut impl Read) -> std::io::Result<Vec<u8>> {
let mut buf = Vec::new();
reader.read_to_end(&mut buf)?;
Ok(buf)
}
fn process<T: Display + Send + 'static>(item: T) -> String {
format!("processed: {item}")
}
동적 디스패치를 위한 트레이트 객체
trait Handler: Send + Sync {
fn handle(&self, request: &Request) -> Response;
}
struct Router {
handlers: Vec<Box<dyn Handler>>,
}
fn fast_process<H: Handler>(handler: &H, request: &Request) -> Response {
handler.handle(request)
}
타입 안전성을 위한 뉴타입(Newtype) 패턴
struct UserId(u64);
struct OrderId(u64);
fn get_order(user: UserId, order: OrderId) -> Result<Order> {
todo!()
}
fn get_order_bad(user_id: u64, order_id: u64) -> Result<Order> {
todo!()
}
구조체 및 데이터 모델링
복잡한 생성을 위한 빌더 패턴
struct ServerConfig {
host: String,
port: u16,
max_connections: usize,
}
impl ServerConfig {
fn builder(host: impl Into<String>, port: u16) -> ServerConfigBuilder {
ServerConfigBuilder { host: host.into(), port, max_connections: 100 }
}
}
struct ServerConfigBuilder { host: String, port: u16, max_connections: usize }
impl ServerConfigBuilder {
fn max_connections(mut self, n: usize) -> Self { self.max_connections = n; self }
fn build(self) -> ServerConfig {
ServerConfig { host: self.host, port: self.port, max_connections: self.max_connections }
}
}
반복자(Iterators) 및 클로저(Closures)
수동 루프보다 반복자 체인 선호
let active_emails: Vec<String> = users.iter()
.filter(|u| u.is_active)
.map(|u| u.email.clone())
.collect();
let mut active_emails = Vec::new();
for user in &users {
if user.is_active {
active_emails.push(user.email.clone());
}
}
타입 어노테이션과 함께 collect() 사용
let names: Vec<_> = items.iter().map(|i| &i.name).collect();
let lookup: HashMap<_, _> = items.iter().map(|i| (i.id, i)).collect();
let combined: String = parts.iter().copied().collect();
let parsed: Result<Vec<i32>, _> = strings.iter().map(|s| s.parse()).collect();
동시성 (Concurrency)
공유 가변 상태를 위한 Arc<Mutex>
use std::sync::{Arc, Mutex};
let counter = Arc::new(Mutex::new(0));
let handles: Vec<_> = (0..10).map(|_| {
let counter = Arc::clone(&counter);
std::thread::spawn(move || {
let mut num = counter.lock().expect("mutex poisoned");
*num += 1;
})
}).collect();
for handle in handles {
handle.join().expect("worker thread panicked");
}
메시지 전달을 위한 채널
use std::sync::mpsc;
let (tx, rx) = mpsc::sync_channel(16);
for i in 0..5 {
let tx = tx.clone();
std::thread::spawn(move || {
tx.send(format!("message {i}")).expect("receiver disconnected");
});
}
drop(tx);
for msg in rx {
println!("{msg}");
}
Tokio를 사용한 비동기
use tokio::time::Duration;
async fn fetch_with_timeout(url: &str) -> Result<String> {
let response = tokio::time::timeout(
Duration::from_secs(5),
reqwest::get(url),
)
.await
.context("request timed out")?
.context("request failed")?;
response.text().await.context("failed to read body")
}
async fn fetch_all(urls: Vec<String>) -> Vec<Result<String>> {
let handles: Vec<_> = urls.into_iter()
.map(|url| tokio::spawn(async move {
fetch_with_timeout(&url).await
}))
.collect();
let mut results = Vec::with_capacity(handles.());
handles {
results.(handle..(|e| ()));
}
results
}
Unsafe 코드
Unsafe가 허용되는 경우
unsafe fn widget_from_raw<'a>(ptr: *const Widget) -> &'a Widget {
unsafe { &*ptr }
}
unsafe { slice.get_unchecked(index) }
Unsafe가 허용되지 않는 경우
모듈 시스템 및 크레이트 구조
타입이 아닌 도메인별로 조직화
my_app/
├── src/
│ ├── main.rs
│ ├── lib.rs
│ ├── auth/ # 도메인 모듈
│ │ ├── mod.rs
│ │ ├── token.rs
│ │ └── middleware.rs
│ ├── orders/ # 도메인 모듈
│ │ ├── mod.rs
│ │ ├── model.rs
│ │ └── service.rs
│ └── db/ # 인프라
│ ├── mod.rs
│ └── pool.rs
├── tests/ # 통합 테스트
├── benches/ # 벤치마크
└── Cargo.toml
가시성 — 최소한으로 노출
pub(crate) fn validate_input(input: &str) -> bool {
!input.is_empty()
}
pub mod auth;
pub use auth::AuthMiddleware;
pub fn internal_helper() {}
도구 통합 (Tooling Integration)
필수 명령어
cargo build
cargo check
cargo clippy
cargo fmt
cargo test
cargo test -- --nocapture
cargo test --lib
cargo test --test integration
cargo audit
cargo tree
cargo update
cargo bench
빠른 참조: 러스트 관용구
| 관용구 | 설명 |
|---|
| 복제 대신 빌림 | 소유권이 필요한 경우가 아니면 복제 대신 &T 전달 |
| 유효하지 않은 상태 표현 금지 | 유효한 상태만 모델링하도록 열거형 사용 |
unwrap()보다 ? | 에러를 전파하고, 라이브러리/프로덕션 코드에서 패닉 지양 |
| 검증 대신 파싱 | 경계에서 비구조화된 데이터를 타입화된 구조체로 변환 |
| 안전성을 위한 뉴타입 | 인자 혼동을 막기 위해 원시 타입을 뉴타입으로 감쌈 |
| 루프보다 반복자 선호 | 선언적 체인이 더 명확하고 종종 더 빠름 |
Result에 #[must_use] | 호출자가 반환값을 처리하도록 보장 |
유연한 소유권을 위한 Cow | 빌림으로 충분할 때 할당 피하기 |
| 철저한 매칭 | 비즈니스 크리티컬 열거형에 와일드카드 _ 지양 |
최소한의 pub 노출 | 내부 API에는 pub(crate) 사용 |
피해야 할 안티 패턴
let value = map.get("key").unwrap();
let data = expensive_data.clone();
process(&original, &data);
fn greet(name: String) { }
fn parse(input: &str) -> Result<Data, Box<dyn std::error::Error>> { todo!() }
let _ = validate(input);
async fn bad_async() {
std::thread::sleep(Duration::from_secs(1));
}
기억하세요: 컴파일이 된다면 아마 맞을 것입니다 — 단, unwrap()을 피하고, unsafe를 최소화하며, 타입 시스템이 당신을 위해 일하게 할 때만 해당됩니다.