Skip to content

4.15 Patterns #224

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 24, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 104 additions & 56 deletions 1.9/ja/book/patterns.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
% パターン
<!-- % Patterns -->

<!-- Patterns are quite common in Rust. -->
<!-- Patterns are quite common in Rust. We use them in [variable -->
<!-- bindings][bindings], [match expressions][match], and other places, too. Let’s go -->
<!-- on a whirlwind tour of all of the things patterns can do!-->
パターンはRustにおいて極めて一般的です。

<!-- We use them in [variable
bindings][bindings], [match statements][match], and other places, too.-->
パターンは [変数束縛][bindings], [マッチ文][match] などで使われています。

<!--Let’s go on a whirlwind tour of all of the things patterns can do!-->
さあ、めくるめくパターンの旅を始めましょう!

[bindings]: variable-bindings.html
[match]: match.html

<!-- A quick refresher: you can match against literals directly, and `_` acts as an
‘any’ case: -->
簡単な復習:リテラルに対しては直接マッチさせられます。また、 `_` は「任意の」ケースとして振る舞います。
簡単な復習:リテラルに対しては直接マッチ出来ます。
また、 `_` は「任意の」ケースとして振る舞います。

```rust
let x = 1;
Expand All @@ -32,11 +30,14 @@ match x {
<!-- This prints `one`. -->
これは `one` を表示します。

<!-- There’s one pitfall with patterns: like anything that introduces a new binding,they introduce shadowing. For example: -->
パターンには一つ落とし穴があります。新しい束縛を導入すると、他の束縛を導入するものと同じように、シャドーイングします。例えば:
<!-- There’s one pitfall with patterns: like anything that introduces a new binding, -->
<!-- they introduce shadowing. For example: -->
パターンには一つ落とし穴があります。
新しい束縛を導入すると、他の束縛を導入するものと同じように、シャドーイングします。
例えば:

```rust
let x = 'x';
let x = 1;
let c = 'c';

match c {
Expand All @@ -51,13 +52,18 @@ println!("x: {}", x)

```text
x: c c: c
x: x
x: 1
```

<!-- In other words, `x =>` matches the pattern and introduces a new binding named
`x` that’s in scope for the match arm. Because we already have a binding named
`x`, this new `x` shadows it. -->
別の言い方をすると、 `x =>` はパターンへのマッチだけでなく、マッチの腕内で有効な `x` という名前の束縛を導入します。既に `x` は束縛されていたので、この新しい `x` はそれを覆い隠します。
<!-- In other words, `x =>` matches the pattern and introduces a new binding named -->
<!-- `x`. This new binding is in scope for the match arm and takes on the value of -->
<!-- `c`. Notice that the value of `x` outside the scope of the match has no bearing -->
<!-- on the value of `x` within it. Because we already have a binding named `x`, this -->
<!-- new `x` shadows it. -->
別の言い方をすると、 `x =>` はパターンへにマッチし `x` という名前の束縛を導入します。
この束縛はマッチの腕で有効で、 `c` の値を引き受けます。
マッチのスコープ外にある `x` は内部での `x` の値に関係していないことに注意して下さい。
既に `x` は束縛されていたので、この新しい `x` はそれを覆い隠します。

<!-- # Multiple patterns -->
# 複式パターン
Expand All @@ -82,9 +88,9 @@ match x {
<!-- # Destructuring -->
# デストラクチャリング

<!-- If you have a compound data type, like a [`struct`][struct], you can destructure it
inside of a pattern: -->
例えば [`struct`][struct] のような複合データ型を作成したいとき、パターン内でデータを分解することができます。
<!-- If you have a compound data type, like a [`struct`][struct], you can destructure it -->
<!-- inside of a pattern: -->
例えば [`struct`][struct] のような複合データ型があるとき、パターン内でデータを分解することができます。

```rust
struct Point {
Expand Down Expand Up @@ -136,8 +142,8 @@ match origin {
<!-- This prints `x is 0`. -->
これは `x is 0` を出力します。

<!-- You can do this kind of match on any member, not just the first:-->
どのメンバに対してもこの種のマッチを行うことができます。たとえ最初ではなくても:
<!-- You can do this kind of match on any member, not only the first: -->
最初のものだけでなく、どのメンバに対してもこの種のマッチを行うことができます。

```rust
struct Point {
Expand All @@ -155,8 +161,8 @@ match origin {
<!-- This prints `y is 0`. -->
これは `y is 0` を出力します。

<!-- This ‘destructuring’ behavior works on any compound data type, like
[tuples][tuples] or [enums][enums]. -->
<!-- This ‘destructuring’ behavior works on any compound data type, like -->
<!-- [tuples][tuples] or [enums][enums]. -->
この「デストラクチャリング(destructuring)」と呼ばれる振る舞いは、 [タプル][tuples] や [列挙型][enums] のような、複合データ型で使用できます。

[tuples]: primitive-types.html#tuples
Expand All @@ -166,9 +172,8 @@ match origin {
# 束縛の無視

<!-- You can use `_` in a pattern to disregard the type and value.-->
パターン内の型や値を無視するために `_` を使うことができます。

<!-- For example, here’s a `match` against a `Result<T, E>`: -->
パターン内の型や値を無視するために `_` を使うことができます。
例として、 `Result<T, E>` に対して `match` を適用してみましょう:

```rust
Expand All @@ -179,14 +184,16 @@ match some_value {
}
```

<!-- In the first arm, we bind the value inside the `Ok` variant to `value`. But
in the `Err` arm, we use `_` to disregard the specific error, and just print
a general error message. -->
最初の部分では `Ok` ヴァリアント内の値を `value` に結びつけています。しかし `Err` 部分では、特定のエラーを避けて、標準的なエラーメッセージを表示するために `_` を使っています。
<!-- In the first arm, we bind the value inside the `Ok` variant to `value`. But -->
<!-- in the `Err` arm, we use `_` to disregard the specific error, and print -->
<!-- a general error message. -->
最初の部分では `Ok` ヴァリアント内の値を `value` に束縛しています。
しかし `Err` 部分では、`_` を使って特定のエラーを無視し、一般的なエラーメッセージを表示しています。

<!-- `_` is valid in any pattern that creates a binding. This can be useful to
ignore parts of a larger structure: -->
`_` は束縛を伴うどんなパターンにおいても有効です。これは大きな構造の一部分を無視する際に有用です。
<!-- `_` is valid in any pattern that creates a binding. This can be useful to -->
<!-- ignore parts of a larger structure: -->
`_` は束縛を伴うどんなパターンにおいても有効です。
これは大きな構造の一部分を無視する際に有用です。

```rust
fn coordinate() -> (i32, i32, i32) {
Expand All @@ -198,12 +205,51 @@ fn coordinate() -> (i32, i32, i32) {
let (x, _, z) = coordinate();
```

<!-- Here, we bind the first and last element of the tuple to `x` and `z`, but
ignore the middle element. -->
<!-- Here, we bind the first and last element of the tuple to `x` and `z`, but -->
<!-- ignore the middle element. -->
ここでは、タプルの最初と最後の要素を `x` と `z` に結びつけています。

<!-- Similarly, you can use `..` in a pattern to disregard multiple values. -->
同様に `..` でパターン内の複数の値を無視することができます。
<!-- It’s worth noting that using `_` never binds the value in the first place, -->
<!-- which means a value may not move: -->
`_` はそもそも値を束縛しない、つまり値がムーブしないということは特筆に値します。

```rust
let tuple: (u32, String) = (5, String::from("five"));

# // Here, tuple is moved, because the String moved:
// これだとタプルはムーブします。何故ならStringがムーブしているからです:
let (x, _s) = tuple;

# // The next line would give "error: use of partially moved value: `tuple`"
// この行は「error: use of partially moved value: `tuple`」を出します。
// println!("Tuple is: {:?}", tuple);

# // However,
// しかしながら、

let tuple = (5, String::from("five"));

# // Here, tuple is _not_ moved, as the String was never moved, and u32 is Copy:
// これだとタプルはムーブ _されません_ 。何故ならStringはムーブされず、u32はCopyだからです:
let (x, _) = tuple;

# // That means this works:
// つまりこれは動きます:
println!("Tuple is: {:?}", tuple);
```

<!-- This also means that any temporary variables will be dropped at the end of the -->
<!-- statement: -->
また、束縛されていない値は文の終わりでドロップされるということでもあります。

```rust
# // Here, the String created will be dropped immediately, as it’s not bound:
// 生成されたStringは束縛されていないので即座にドロップされる
let _ = String::from(" hello ").trim();
```

<!-- You can also use `..` in a pattern to disregard multiple values: -->
複数の値を捨てるのには `..` パターンが使えます。

```rust
enum OptionalTuple {
Expand Down Expand Up @@ -236,15 +282,17 @@ match x {
}
```

<!--This prints `Got a reference to 5`. -->
<!-- This prints `Got a reference to 5`. -->
これは `Got a reference to 5` を出力します。

[ref]: references-and-borrowing.html

<!-- Here, the `r` inside the `match` has the type `&i32`. In other words, the `ref`
keyword _creates_ a reference, for use in the pattern. If you need a mutable
reference, `ref mut` will work in the same way: -->
ここで `match` 内の `r` は `&i32` 型を持っています。言い換えると `ref` キーワードがリファレンスを _作ります_ 。
<!-- Here, the `r` inside the `match` has the type `&i32`. In other words, the `ref` -->
<!-- keyword _creates_ a reference, for use in the pattern. If you need a mutable -->
<!-- reference, `ref mut` will work in the same way: -->
ここで `match` 内の `r` は `&i32` 型を持っています。
言い換えると `ref` キーワードがパターン内で使うリファレンスを _作ります_ 。
ミュータブルなリファレンスが必要なら、 `ref mut` が同じように動作します。

```rust
let mut x = 5;
Expand Down Expand Up @@ -292,7 +340,7 @@ match x {
# 束縛

<!-- You can bind values to names with `@`: -->
`@` で値を名前と結びつけることができます
`@` で値を名前に束縛することができます

```rust
let x = 1;
Expand All @@ -303,8 +351,8 @@ match x {
}
```

<!-- This prints `got a range element 1`. This is useful when you want to
do a complicated match of part of a data structure: -->
<!-- This prints `got a range element 1`. This is useful when you want to -->
<!-- do a complicated match of part of a data structure: -->
これは `got a range element 1` を出力します。
データ構造の一部に対する複雑なマッチが欲しいときに有用です:

Expand All @@ -315,19 +363,19 @@ struct Person {
}

let name = "Steve".to_string();
let mut x: Option<Person> = Some(Person { name: Some(name) });
let x: Option<Person> = Some(Person { name: Some(name) });
match x {
Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a),
_ => {}
}
```

<!--This prints `Some("Steve")`: we’ve bound the inner `name` to `a`.-->
<!-- This prints `Some("Steve")`: we’ve bound the inner `name` to `a`.-->
これは `Some("Steve")` を出力します。内側の `name` を `a` に結びつけます。

<!-- If you use `@` with `|`, you need to make sure the name is bound in each part
of the pattern: -->
もし `|` で `@` を使うときは、パターンのそれぞれの部分が名前と結びついているか確認する必要があります:
<!-- If you use `@` with `|`, you need to make sure the name is bound in each part -->
<!-- of the pattern: -->
もし `|` で `@` を使うときは、必ずそれぞれのパターンが名前と結びついている必要があります。

```rust
let x = 5;
Expand All @@ -341,8 +389,8 @@ match x {
<!-- # Guards -->
# ガード

<!--You can introduce ‘match guards’ with `if`: -->
`if` を使うことでマッチガードを導入することができます
<!-- You can introduce ‘match guards’ with `if`: -->
`if` を使うことで「マッチガード」を導入することができます

```rust
enum OptionalInt {
Expand All @@ -359,10 +407,10 @@ match x {
}
```

<!--This prints `Got an int!`. -->
<!-- This prints `Got an int!`. -->
これは `Got an int!` を出力します。

<!--If you’re using `if` with multiple patterns, the `if` applies to both sides:-->
<!-- If you’re using `if` with multiple patterns, the `if` applies to both sides: -->
複式パターンで `if` を使うと、 `if` は両方に適用されます:

```rust
Expand All @@ -375,8 +423,8 @@ match x {
}
```

<!--This prints `no`, because the `if` applies to the whole of `4 | 5`, and not to
just the `5`. In other words, the precedence of `if` behaves like this: -->
<!-- This prints `no`, because the `if` applies to the whole of `4 | 5`, and not to -->
<!-- only the `5`. In other words, the precedence of `if` behaves like this: -->
これは `no` を出力します。なぜなら `if` は `4 | 5` 全体に適用されるのであって、 `5` 単独に対してではないからです。つまり `if` 節は以下のように振舞います:

```text
Expand All @@ -393,8 +441,8 @@ just the `5`. In other words, the precedence of `if` behaves like this: -->
<!-- # Mix and Match -->
# 混ぜてマッチ

<!--Whew! That’s a lot of different ways to match things, and they can all be
mixed and matched, depending on what you’re doing: -->
<!-- Whew! That’s a lot of different ways to match things, and they can all be -->
<!-- mixed and matched, depending on what you’re doing: -->
ふう、マッチには様々な方法があるのですね。やりたいこと次第で、それらを混ぜてマッチさせることもできます:

```rust,ignore
Expand Down
3 changes: 3 additions & 0 deletions TranslationTable.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
| antipattern | アンチパターン
| application | アプリケーション
| arity | アリティ
| (マッチの)arm | 腕
| array | 配列
| assignment | 代入
| associated - | 関連-
Expand All @@ -44,6 +45,7 @@
| command line | コマンドライン
| compile-time error | コンパイル時エラー
| compiler | コンパイラ
| compound data type | 複合データ型
| composable | 合成可能
| computer science | コンピュータサイエンス
| concurrency | 並行性
Expand Down Expand Up @@ -117,6 +119,7 @@
| lint | リント
| mangling | マングリング
| match | マッチ
| match guards | マッチガード
| memory | メモリ
| method | メソッド
| monomorphization | 単相化
Expand Down
Loading