6
6
7
7
<!--
8
8
The first collection type we’ll look at is `Vec<T>`, also known as a *vector*.
9
- Vectors allow us to store more than one value in a single data structure that
9
+ Vectors allow you to store more than one value in a single data structure that
10
10
puts all the values next to each other in memory. Vectors can only store values
11
11
of the same type. They are useful when you have a list of items, such as the
12
12
lines of text in a file or the prices of items in a shopping cart.
@@ -31,7 +31,7 @@ Listing 8-1.
31
31
新しい空のベクタを作るには、リスト8-1に示されたように、` Vec::new ` 関数を呼べばよいです。
32
32
33
33
``` rust
34
- let v : Vec < i32 > = Vec :: new ();
34
+ {{# rustdoc_include .. / listings / ch08 - common - collections / listing - 08 - 01 / src / main . rs : here }}
35
35
```
36
36
37
37
<!--
@@ -62,19 +62,22 @@ hold elements of the `i32` type.
62
62
<!--
63
63
In more realistic code, Rust can often infer the type of value you want to
64
64
store once you insert values, so you rarely need to do this type annotation.
65
- It' s more common to create a `Vec<T>` that has initial values, and Rust
65
+ It’ s more common to create a `Vec<T>` that has initial values, and Rust
66
66
provides the `vec!` macro for convenience. The macro will create a new vector
67
- that holds the values we give it. Listing 8-2 creates a new `Vec<i32>` that
68
- holds the values `1`, `2`, and `3`.
67
+ that holds the values you give it. Listing 8-2 creates a new `Vec<i32>` that
68
+ holds the values `1`, `2`, and `3`. The integer type is `i32` because that’s
69
+ the default integer type, as we discussed in the [“Data Types”][data-types]
70
+ section of Chapter 3.
69
71
-->
70
72
71
73
より現実的なコードでは、一旦値を挿入したら、コンパイラは保持させたい値の型をしばしば推論できるので、
72
74
この型注釈をすることは滅多にありません。初期値のある` Vec<T> ` を生成する方が一般的ですし、
73
75
Rustには、利便性のために` vec! ` というマクロも用意されています。このマクロは、
74
76
与えた値を保持する新しいベクタ型を生成します。リスト8-2では、` 1 ` 、` 2 ` 、` 3 ` という値を持つ新しい` Vec<i32> ` を生成しています。
77
+ 整数型を` i32 ` にしているのは、3章の[ 「データ型」] [ data-types ] 節で学んだようにこれが標準の整数型だからです。
75
78
76
79
``` rust
77
- let v = vec! [ 1 , 2 , 3 ];
80
+ {{# rustdoc_include .. / listings / ch08 - common - collections / listing - 08 - 02 / src / main . rs : here }}
78
81
```
79
82
80
83
<!--
@@ -107,12 +110,7 @@ as shown in Listing 8-3.
107
110
ベクタを生成し、それから要素を追加するには、リスト8-3に示したように、` push ` メソッドを使用できます。
108
111
109
112
``` rust
110
- let mut v = Vec :: new ();
111
-
112
- v . push (5 );
113
- v . push (6 );
114
- v . push (7 );
115
- v . push (8 );
113
+ {{#rustdoc_include .. / listings / ch08 - common - collections / listing - 08 - 03 / src / main . rs: here }}
116
114
```
117
115
118
116
<!--
@@ -146,28 +144,9 @@ annotated in Listing 8-4.
146
144
147
145
他のあらゆる` 構造体 ` 同様、ベクタもスコープを抜ければ、解放されます。リスト8-4に注釈したようにですね。
148
146
149
- <!--
150
- ```rust
151
- {
152
- let v = vec![1, 2, 3, 4];
153
- -->
154
-
155
- <!--
156
- // do stuff with v
157
- -->
158
-
159
- <!--
160
- } // <- v goes out of scope and is freed here
161
- ```
162
- -->
163
147
164
148
``` rust
165
- {
166
- let v = vec! [1 , 2 , 3 , 4 ];
167
-
168
- // vで作業をする
169
-
170
- } // <- vはここでスコープを抜け、解放される
149
+ {{#rustdoc_include .. / listings / ch08 - common - collections / listing - 08 - 04 / src / main . rs: here }}
171
150
```
172
151
173
152
<!--
@@ -178,7 +157,7 @@ are dropped</span>
178
157
<span class =" caption " >リスト8-4: ベクタとその要素がドロップされる箇所を示す</span >
179
158
180
159
<!--
181
- When the vector gets dropped, all of its contents will also be dropped, meaning
160
+ When the vector gets dropped, all of its contents are also dropped, meaning
182
161
those integers it holds will be cleaned up. This may seem like a
183
162
straightforward point but can get a bit more complicated when you start to
184
163
introduce references to the elements of the vector. Let’s tackle that next!
@@ -213,10 +192,7 @@ indexing syntax or the `get` method.
213
192
リスト8-5に示したのは、両メソッドがベクタの値に対して、添字記法と` get ` メソッドによりアクセスするところです。
214
193
215
194
``` rust
216
- let v = vec! [1 , 2 , 3 , 4 , 5 ];
217
-
218
- let third : & i32 = & v [2 ];
219
- let third : Option <& i32 > = v . get (2 );
195
+ {{#rustdoc_include .. / listings / ch08 - common - collections / listing - 08 - 05 / src / main . rs: here }}
220
196
```
221
197
222
198
<!--
@@ -250,11 +226,8 @@ Rustには要素を参照する方法が2通りあるので、ベクタに要素
250
226
プログラムの振る舞いを選択できます。例として、ベクタに5つ要素があり、添え字100の要素にアクセスを試みた場合、
251
227
プログラムがすることを確認しましょう。リスト8-6に示したようにですね。
252
228
253
- ``` rust,should_panic
254
- let v = vec![1, 2, 3, 4, 5];
255
-
256
- let does_not_exist = &v[100];
257
- let does_not_exist = v.get(100);
229
+ ``` rust,should_panic,panics
230
+ {{#rustdoc_include ../listings/ch08-common-collections/listing-08-06/src/main.rs:here}}
258
231
```
259
232
260
233
<!--
@@ -267,7 +240,7 @@ let does_not_exist = v.get(100);
267
240
<!--
268
241
When we run this code, the first `[]` method will cause the program to panic
269
242
because it references a nonexistent element. This method is best used when you
270
- want your program to crash if there' s an attempt to access an element past the
243
+ want your program to crash if there’ s an attempt to access an element past the
271
244
end of the vector.
272
245
-->
273
246
@@ -298,7 +271,7 @@ value. That would be more user-friendly than crashing the program due to a typo!
298
271
When the program has a valid reference, the borrow checker enforces the
299
272
ownership and borrowing rules (covered in Chapter 4) to ensure this reference
300
273
and any other references to the contents of the vector remain valid. Recall the
301
- rule that states we can’t have mutable and immutable references in the same
274
+ rule that states you can’t have mutable and immutable references in the same
302
275
scope. That rule applies in Listing 8-7, where we hold an immutable reference to
303
276
the first element in a vector and try to add an element to the end, which won't
304
277
work.
@@ -308,16 +281,11 @@ work.
308
281
所有権と借用規則を強制し、ベクタの中身へのこの参照や他のいかなる参照も有効であり続けることを保証してくれます。
309
282
同一スコープ上では、可変と不変な参照を同時には存在させられないというルールを思い出してください。
310
283
このルールはリスト8-7にも適用され、リスト8-7ではベクタの最初の要素への不変参照を保持し、
311
- 終端に要素を追加しようとしていますが、動きません。
312
-
313
- ``` rust,ignore
314
- let mut v = vec![1, 2, 3, 4, 5];
315
-
316
- let first = &v[0];
284
+ 終端に要素を追加しようとしています。
285
+ もし、関数内のここ以降で、この要素を参照しようとしている場合、これは動きません。
317
286
318
- v.push(6);
319
-
320
- println!("The first element is: {}", first);
287
+ ``` rust,ignore,does_not_compile
288
+ {{#rustdoc_include ../listings/ch08-common-collections/listing-08-07/src/main.rs:here}}
321
289
```
322
290
323
291
<!--
@@ -333,28 +301,16 @@ Compiling this code will result in this error:
333
301
334
302
このコードをコンパイルすると、こんなエラーになります:
335
303
336
- ``` text
337
- error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
338
- (エラー: 不変としても借用されているので、`v`を可変で借用できません)
339
- |
340
- 4 | let first = &v[0];
341
- | - immutable borrow occurs here
342
- | (不変借用はここで発生しています)
343
- 5 |
344
- 6 | v.push(6);
345
- | ^ mutable borrow occurs here
346
- | (可変借用は、ここで発生しています)
347
- 7 | }
348
- | - immutable borrow ends here
349
- | (不変借用はここで終了しています)
304
+ ``` console
305
+ {{#include ../listings/ch08-common-collections/listing-08-07/output.txt}}
350
306
```
351
307
352
308
<!--
353
309
The code in Listing 8-7 might look like it should work: why should a reference
354
310
to the first element care about what changes at the end of the vector? This
355
311
error is due to the way vectors work: adding a new element onto the end of the
356
312
vector might require allocating new memory and copying the old elements to the
357
- new space if there isn’t enough room to put all the elements next to each
313
+ new space, if there isn’t enough room to put all the elements next to each
358
314
other where the vector currently is. In that case, the reference to the first
359
315
element would be pointing to deallocated memory. The borrowing rules prevent
360
316
programs from ending up in that situation.
@@ -368,25 +324,25 @@ programs from ending up in that situation.
368
324
そのような場面に陥らないよう回避されるのです。
369
325
370
326
<!--
371
- > Note: For more on the implementation details of the `Vec<T>` type, see “The
372
- > Rustonomicon” at https://doc.rust-lang.org/stable/ nomicon/vec.html .
327
+ > Note: For more on the implementation details of the `Vec<T>` type, see [ “The
328
+ > Rustonomicon”][ nomicon] .
373
329
-->
374
330
375
- > 注釈: ` Vec<T> ` の実装に関する詳細については、[ “The Rustonomicon”] ( https://doc.rust-lang.org/stable/ nomicon/vec.html ) を参照してください。
331
+ > 注釈: ` Vec<T> ` の実装に関する詳細については、[ “The Rustonomicon”] [ nomicon ] を参照してください。
376
332
377
333
> 訳注: 日本語版のThe Rustonomiconは[ こちら] [ nomicon-ja-vec ] です。
378
334
379
335
[ nomicon-ja-vec ] : https://doc.rust-jp.rs/rust-nomicon-ja/vec.html
380
336
381
337
<!--
382
- ### Iterating Over the Values in a Vector
338
+ ### Iterating over the Values in a Vector
383
339
-->
384
340
385
341
### ベクタの値を走査する
386
342
387
343
<!--
388
344
If we want to access each element in a vector in turn, we can iterate through
389
- all of the elements rather than use indexes to access one at a time. Listing
345
+ all of the elements rather than use indices to access one at a time. Listing
390
346
8-8 shows how to use a `for` loop to get immutable references to each element
391
347
in a vector of `i32` values and print them.
392
348
-->
@@ -395,10 +351,7 @@ in a vector of `i32` values and print them.
395
351
リスト8-8で` for ` ループを使い、` i32 ` のベクタの各要素に対する不変な参照を得て、それらを出力する方法を示しています。
396
352
397
353
``` rust
398
- let v = vec! [100 , 32 , 57 ];
399
- for i in & v {
400
- println! (" {}" , i );
401
- }
354
+ {{#rustdoc_include .. / listings / ch08 - common - collections / listing - 08 - 08 / src / main . rs: here }}
402
355
```
403
356
404
357
<!--
@@ -418,10 +371,7 @@ will add `50` to each element.
418
371
リスト8-9の` for ` ループでは、各要素に` 50 ` を足しています。
419
372
420
373
``` rust
421
- let mut v = vec! [100 , 32 , 57 ];
422
- for i in & mut v {
423
- * i += 50 ;
424
- }
374
+ {{#rustdoc_include .. / listings / ch08 - common - collections / listing - 08 - 09 / src / main . rs: here }}
425
375
```
426
376
427
377
<!--
@@ -434,11 +384,14 @@ elements in a vector</span>
434
384
<!--
435
385
To change the value that the mutable reference refers to, we have to use the
436
386
dereference operator (`*`) to get to the value in `i` before we can use the
437
- `+=` operator.
387
+ `+=` operator. We’ll talk more about the dereference operator in the
388
+ [“Following the Pointer to the Value with the Dereference Operator”][deref]
389
+ section of Chapter 15.
438
390
-->
439
391
440
392
可変参照が参照している値を変更するには、` += ` 演算子を使用する前に、
441
393
参照外し演算子(` * ` )を使用して` i ` の値に辿り着かないといけません。
394
+ 参照外し演算子については、15章の[ 「参照外し演算子で値までポインタを追いかける」] [ deref ] 節でより詳しく扱います。
442
395
443
396
<!--
444
397
### Using an Enum to Store Multiple Types
@@ -474,17 +427,7 @@ ultimately, holds different types. We’ve demonstrated this in Listing 8-10.
474
427
結果的に異なる型を保持できるようになるわけです。リスト8-10でこれを模擬しています。
475
428
476
429
``` rust
477
- enum SpreadsheetCell {
478
- Int (i32 ),
479
- Float (f64 ),
480
- Text (String ),
481
- }
482
-
483
- let row = vec! [
484
- SpreadsheetCell :: Int (3 ),
485
- SpreadsheetCell :: Text (String :: from (" blue" )),
486
- SpreadsheetCell :: Float (10.12 ),
487
- ];
430
+ {{#rustdoc_include .. / listings / ch08 - common - collections / listing - 08 - 10 / src / main . rs: here }}
488
431
```
489
432
490
433
<!--
@@ -513,7 +456,7 @@ enumに加えて`match`式を使うことは、第6章で議論した通り、
513
456
保証できることを意味します。
514
457
515
458
<!--
516
- When you' re writing a program, if you don’t know the exhaustive set of types
459
+ When you’ re writing a program, if you don’t know the exhaustive set of types
517
460
the program will get at runtime to store in a vector, the enum technique won’t
518
461
work. Instead, you can use a trait object, which we’ll cover in Chapter 17.
519
462
-->
@@ -523,7 +466,7 @@ work. Instead, you can use a trait object, which we’ll cover in Chapter 17.
523
466
524
467
<!--
525
468
Now that we’ve discussed some of the most common ways to use vectors, be sure
526
- to review the API documentation for all the many useful methods defined on
469
+ to review [ the API documentation][vec-api] for all the many useful methods defined on
527
470
`Vec<T>` by the standard library. For example, in addition to `push`, a `pop`
528
471
method removes and returns the last element. Let’s move on to the next
529
472
collection type: `String`!
@@ -534,5 +477,17 @@ collection type: `String`!
534
477
-->
535
478
536
479
今や、ベクタを使用するべき最も一般的な方法について触れ、議論したので、標準ライブラリで` Vec<T> ` に定義されている多くの有益なメソッドについては、
537
- APIドキュメントを確認することを心得てください 。例として、` push ` に加えて、` pop ` メソッドは最後の要素を削除して返します。
480
+ [ APIドキュメント ] [ vec-api ] を確認することを心得てください 。例として、` push ` に加えて、` pop ` メソッドは最後の要素を削除して返します。
538
481
次のコレクション型に移りましょう: ` String ` です!
482
+
483
+ <!--
484
+ [data-types]: ch03-02-data-types.html#data-types
485
+ [nomicon]: ../nomicon/vec.html
486
+ [vec-api]: ../std/vec/struct.Vec.html
487
+ [deref]: ch15-02-deref.html#following-the-pointer-to-the-value-with-the-dereference-operator
488
+ -->
489
+
490
+ [ data-types ] : ch03-02-data-types.html#データ型
491
+ [ nomicon ] : ../nomicon/vec.html
492
+ [ vec-api ] : ../std/vec/struct.Vec.html
493
+ [ deref ] : ch15-02-deref.html#参照外し演算子で値までポインタを追いかける
0 commit comments