0
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の「アンダースコア」の意味について

Posted at

Rust では *_(アンダースコア)には 「無視する(不要な値)」 という意味があります。

通常、関数の引数やタプルの一部を 使わない場合、Rust では警告が出ることがあります。 その時に let _ を使うことで 未使用変数の警告を回避 できます。

ふつうに変数を無視すると・・・

fn main() {
    let x = 10;
}

このように実行すると・・・

warning: unused variable: `x`
 --> src/main.rs:2:9
  |
2 |     let x = 10;
  |         ^ help: if this is intentional, prefix it with an underscore: `_x`

警告が出る


_ を使うことで意図的に使わないことをアピール

fn main() {
    let _x = 10; // _x は使わなくても警告が出ない
}

_x という変数名にすることで、「この変数は意図的に使わない」と Rust に伝えられる。

fn main() {
let _ = 10; // 何もしない(変数を一切作らない)
}
_ = 10; は「値 10 を使わずに捨てる」ことを意味する。

使用例

タプルの一部を無視する

fn main() {
    let tup = (1, 2, 3);

    let (a, _, c) = tup; // 2 を無視
    println!("a: {}, c: {}", a, c);
}

output

a: 1, c: 3

enumerate() のインデックスを無視

fn main() {
    let arr = [10, 20, 30];

    for (_, value) in arr.iter().enumerate() {
        println!("{}", value);
    }
}

output

10
20
30

関数の引数を無視する

fn unused_param(_x: i32) {
    // `_x` を使わないが警告は出ない
}

_ を型のプレースホルダーとして使う

型推論を Rust に任せる

fn main() {
    let num: _ = 10; // Rust が型 `i32` を推測
    println!("{}", num);
}

Vec の型を _ で省略

fn main() {
    let v: Vec<_> = vec![1, 2, 3]; // Rust が `Vec<i32>` だと推測
}

match 式で _ をワイルドカードとして使う

fn main() {
    let number = 5;

    match number {
        1 => println!("1です"),
        2 => println!("2です"),
        _ => println!("その他の数字です"),
    }
}

output

その他の数字です

_ を関数の戻り値で使う

Ok(_) で成功時の値を無視

fn main() {
    let result: Result<i32, &str> = Ok(42);

    match result {
        Ok(_) => println!("成功"),
        Err(err) => println!("エラー: {}", err),
    }
}

output

成功

_ をジェネリック型のプレースホルダーとして使う

ジェネリック型 T などを _ で省略できる。
::<_> を使うことで、Rust に型推論を任せる。

fn add<T: std::ops::Add<Output = T>> (a: T, b: T) -> T {
    a + b
}

fn main() {
    let result = add::<_>(10, 20); // Rust が型を自動推測
    println!("{}", result);
}
0
0
2

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
0
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?