let x = 5; | 불변 변수 |
let mut x = 5; | 가변 변수 |
const MAX: i32 = 100; | 상수 |
let x: i32 = 5; | 타입 주석 |
i8, i16, i32, i64, i128, isize | 부호 있는 정수 |
u8, u16, u32, u64, u128, usize | 부호 없는 정수 |
f32, f64 | 부동 소수점 |
bool | 불리언 |
char | 유니코드 문자 |
&str / String | 문자열 슬라이스 / 소유 문자열 |
+ - * / % | 산술 |
== != < > <= >= | 비교 |
&& || ! | 논리 |
& | ^ << >> | 비트 |
&x | 참조 |
*x | 역참조 |
.. | 범위 (배타적) |
..= | 범위 (포함) |
let s2 = s1; | 소유권 이동 |
let s2 = s1.clone(); | 깊은 복사 |
&T | 불변 참조 |
&mut T | 가변 참조 |
fn f(s: &String) {} | 빌림 매개변수 |
fn f(s: &mut String) {} | 가변 빌림 |
&'a T | 라이프타임이 있는 참조 |
fn f<'a>(x: &'a str) -> &'a str | 라이프타임 주석 |
&'static str | 정적 라이프타임 |
struct S<'a> { x: &'a str } | 라이프타임이 있는 구조체 |
if cond { } else { } | if-else |
let x = if cond { a } else { b }; | if 표현식 |
if let Some(x) = opt { } | if let |
while let Some(x) = iter.next() { } | while let |
loop { } | 무한 루프 |
while cond { } | while 루프 |
for x in iter { } | for 루프 |
for i in 0..10 { } | 범위 루프 |
break / continue | 루프 제어 |
break 'label value | 값과 함께 break |
'label: loop { } | 레이블 루프 |
match x { 1 => a, 2 => b, _ => c } | match 표현식 |
1 | 2 | 3 => ... | 다중 패턴 |
1..=5 => ... | 범위 패턴 |
Some(x) => ... | 열거형 구조 분해 |
if guard => ... | 매치 가드 |
@ binding | 변수에 바인딩 |
let v: Vec<i32> = Vec::new(); | 벡터 생성 |
let v = vec![1, 2, 3]; | 벡터 매크로 |
v.push(x) / v.pop() | 추가/제거 |
v[i] / v.get(i) | 요소 접근 |
&v[..] / &v[1..3] | 슬라이스 |
HashMap::new() | HashMap 생성 |
map.insert(k, v) | 맵에 삽입 |
map.get(&k) | 맵에서 가져오기 |
HashSet::new() | HashSet 생성 |
struct Name { field: Type } | 명명된 구조체 |
struct Point(i32, i32); | 튜플 구조체 |
struct Unit; | 유닛 구조체 |
Name { field: value } | 인스턴스화 |
Name { field, ..other } | 구조체 업데이트 |
enum E { A, B(i32), C { x: i32 } } | 열거형 변형 |
Option<T>: Some(x) / None | Option 타입 |
Result<T, E>: Ok(x) / Err(e) | Result 타입 |
fn name(a: i32, b: i32) -> i32 { } | 함수 정의 |
fn name() { } // returns () | 반환 없음 (유닛) |
expression // implicit return | 암시적 반환 |
return value; | 명시적 반환 |
|x| x + 1 | 클로저 |
|x: i32| -> i32 { x + 1 } | 타입 있는 클로저 |
move || { } | move 클로저 |
impl Name { fn method(&self) { } } | 메서드 정의 |
&self | 불변 self |
&mut self | 가변 self |
self | 소비 self |
Self | impl 타입의 별칭 |
fn new() -> Self { } | 연관 함수 |
trait Name { fn method(&self); } | 트레이트 정의 |
impl Trait for Type { } | 트레이트 구현 |
fn f(x: impl Trait) | impl 트레이트 매개변수 |
fn f(x: &dyn Trait) | 트레이트 객체 |
Box<dyn Trait> | 박스된 트레이트 객체 |
#[derive(Debug, Clone)] | derive 매크로 |
fn f<T>(x: T) { } | 제네릭 함수 |
struct S<T> { field: T } | 제네릭 구조체 |
fn f<T: Trait>(x: T) | 트레이트 바운드 |
fn f<T: A + B>(x: T) | 다중 바운드 |
where T: Trait | where 절 |
impl<T> S<T> { } | 제네릭 impl |
result? | 에러 전파 |
result.unwrap() | Err이면 panic |
result.expect("msg") | 메시지와 함께 panic |
result.unwrap_or(default) | 기본값 |
result.unwrap_or_else(|| ...) | 지연 기본값 |
option.map(|x| ...) | 값 변환 |
option.and_then(|x| ...) | 플랫 맵 |
option.ok_or(err) | Option을 Result로 |
#[derive(Debug)] | Debug derive |
impl std::error::Error for E { } | Error 구현 |
impl std::fmt::Display for E { } | Display 구현 |
thiserror::Error | thiserror 크레이트 |
anyhow::Error | anyhow 크레이트 |
cargo new project | 새 프로젝트 생성 |
cargo build | 프로젝트 빌드 |
cargo build --release | 최적화 빌드 |
cargo run | 프로젝트 실행 |
cargo test | 테스트 실행 |
cargo check | 빌드 없이 검사 |
cargo clippy | 코드 린트 |
cargo fmt | 코드 포맷 |
cargo doc --open | 문서 생성 |
cargo add crate | 의존성 추가 |
clippy와 rustfmt 사용String보다 &str 선호? 연산자 사용unwrap()보다 match나 if let 선호derive 사용Option 사용