🦀 Rustチートシート

基本構文

構文用途
let x = 値;不変変数let name = "Rust";
let mut x = 値;可変変数let mut count = 0;
const X: T = 値;定数const MAX: u32 = 100;
println!()出力println!("Hello");
println!("{}", x)フォーマット出力println!("{} is {}", name, age);

所有権(Ownership)

概念説明
所有権の移動代入で所有権が移るlet s2 = s1; // s1は使えない
&T(参照)不変借用fn len(s: &String) -> usize
&mut T可変借用fn push(s: &mut String)
.clone()深いコピーlet s2 = s1.clone();
'a(ライフタイム)参照の有効期間fn f<'a>(s: &'a str) -> &'a str

データ構造

用途
Vec<T>可変長配列let v = vec![1, 2, 3];
HashMap<K, V>キーと値のペアlet mut m = HashMap::new();
struct構造体struct User { name: String, age: u32 }
enum列挙型enum Color { Red, Green, Blue }
Option<T>値があるかもしれないlet x: Option<i32> = Some(5);

制御構文

構文用途
if / else条件分岐if x > 0 { ... } else { ... }
loop無限ループloop { break; }
while条件付きループwhile x > 0 { x -= 1; }
for inイテレータ走査for item in vec.iter() { ... }
matchパターンマッチmatch x { 1 => "one", _ => "other" }

エラーハンドリング

構文用途
Result<T, E>成功or失敗fn read() -> Result<String, io::Error>
?演算子エラー伝搬let data = fs::read_to_string("f.txt")?;
unwrap()値を取り出す(失敗でpanic)let v = result.unwrap();
expect()メッセージ付きunwraplet v = result.expect("failed");
match Result明示的なエラー処理match result { Ok(v) => v, Err(e) => ... }

トレイト

構文用途
trait Nameトレイト定義trait Greet { fn hello(&self); }
impl Trait for Tトレイト実装impl Greet for User { ... }
#[derive(...)]自動実装#[derive(Debug, Clone)]
impl Tメソッド定義impl User { fn new() -> Self { ... } }

Cargo(パッケージ管理)

コマンド用途
cargo newプロジェクト作成cargo new myapp
cargo buildビルドcargo build --release
cargo runビルド&実行cargo run
cargo testテスト実行cargo test
cargo add依存追加cargo add serde

← チートシート一覧に戻る