1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rust「よく使う文法」だけ押さえると一気にわかる

1
Posted at

1. 変数と不変 / 可変(Rustの基本思想)

let x = 10;        // 不変(デフォルト)
let mut y = 20;    // 可変
y += 5;

mutを付けないと変更不可
・「勝手に変わらない」=バグを防ぎやすい


2. 型指定(省略できるが重要)

let a: i32 = 100;
let b = 3.14; // f64と推論される

型が曖昧なときは明示するとエラー回避しやすい。


3. 関数定義と戻り値

fn add(x: i32, y: i32) -> i32 {
    x + y   // セミコロンなし=戻り値
}

・Rustは式指向
returnは省略が基本


4. if は「式」

let n = 5;

let result = if n % 2 == 0 {
    "even"
} else {
    "odd"
};

・三項演算子の代わり
・ifの各ブロックは同じ型にする


5. match(超重要)

let x = 3;

match x {
    1 => println!("one"),
    2 | 3 => println!("two or three"),
    _ => println!("other"),
}

・switchの上位互換
網羅性チェックが強力


6. 所有権(最初の壁)

let s1 = String::from("hello");
let s2 = s1; // 所有権が移動

// println!("{}", s1); // コンパイルエラー

・ヒープデータは「持ち主が1人」
・移動後は使えない


7. 借用(参照)

fn print_len(s: &String) {
    println!("{}", s.len());
}

let s = String::from("hello");
print_len(&s); // 所有権は移らない

可変借用

fn add_world(s: &mut String) {
    s.push_str(" world");
}

let mut s = String::from("hello");
add_world(&mut s);

・可変参照は同時に1つだけ
→ データ競合をコンパイル時に防ぐ


8. 構造体(struct)

struct User {
    name: String,
    age: u32,
}

let user = User {
    name: String::from("Taro"),
    age: 30,
};

impl(メソッド)

impl User {
    fn greet(&self) {
        println!("Hello, {}", self.name);
    }
}

9. enum(Rustの真骨頂)

enum Status {
    Success,
    Error(String),
}
let s = Status::Error("Not found".to_string());

match s {
    Status::Success => println!("OK"),
    Status::Error(msg) => println!("Error: {}", msg),
}

・値を持てるenum
・エラー処理で超頻出


10. Option と Result(最重要)

Option

let v = Some(10);

match v {
    Some(x) => println!("{}", x),
    None => println!("no value"),
}

Result

fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err("division by zero".to_string())
    } else {
        Ok(a / b)
    }
}
match divide(10, 2) {
    Ok(n) => println!("{}", n),
    Err(e) => println!("error: {}", e),
}

11. ? 演算子(エラー伝播)

fn read_file() -> Result<String, std::io::Error> {
    let content = std::fs::read_to_string("test.txt")?;
    Ok(content)
}

Errなら即return
・実務コードはこれだらけ


12. Vec(配列)

let mut v = vec![1, 2, 3];
v.push(4);

for x in &v {
    println!("{}", x);
}

13. HashMap

use std::collections::HashMap;

let mut map = HashMap::new();
map.insert("apple", 3);
map.insert("banana", 2);

if let Some(v) = map.get("apple") {
    println!("{}", v);
}

14. for / while / loop

for i in 0..3 {
    println!("{}", i);
}
let mut n = 0;
while n < 3 {
    n += 1;
}
loop {
    break;
}

15. if let / while let(match簡略形)

let x = Some(5);

if let Some(v) = x {
    println!("{}", v);
}

実務での優先度まとめ

🔥 最優先
・所有権 / 借用
・Option / Result
・match / enum

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?