1
1
# ` read_lines `
2
2
3
+ <!--
3
4
## A naive approach
5
+ -->
6
+ ## 単純なやり方
4
7
8
+ <!--
5
9
This might be a reasonable first attempt for a beginner's first
6
10
implementation for reading lines from a file.
11
+ -->
12
+ テキストファイルの行を読み込むのを、初心者が初めて実装した場合、
13
+ 以下のようになるでしょう。
7
14
8
15
``` rust,norun
9
16
use std::fs::read_to_string;
@@ -19,33 +26,57 @@ fn read_lines(filename: &str) -> Vec<String> {
19
26
}
20
27
```
21
28
29
+ <!--
22
30
Since the method `lines()` returns an iterator over the lines in the file,
23
31
we can also perform a map inline and collect the results, yielding a more
24
32
concise and fluent expression.
33
+ -->
34
+ ` lines() ` メソッドはファイルの各行のイテレータを返すので、
35
+ インラインでマップを実行し結果を収集することもできます。
36
+ そうすると、より簡潔で読みやすい表現となります。
25
37
26
38
``` rust,norun
27
39
use std::fs::read_to_string;
28
40
29
41
fn read_lines(filename: &str) -> Vec<String> {
30
42
read_to_string(filename)
31
43
.unwrap() // panic on possible file-reading errors
44
+ // ファイル読み込みエラーの場合はパニックする。
32
45
.lines() // split the string into an iterator of string slices
46
+ // 文字列のスライスのイテレータに分割する。
33
47
.map(String::from) // make each slice into a string
48
+ // スライスを文字列に変換する。
34
49
.collect() // gather them together into a vector
50
+ // ベクタにまとめる。
35
51
}
36
52
```
37
53
54
+ <!--
38
55
Note that in both examples above, we must convert the `&str` reference
39
56
returned from `lines()` to the owned type `String`, using `.to_string()`
40
57
and `String::from` respectively.
58
+ -->
59
+ 上の例では、` lines() ` から返された` &str ` を
60
+ それぞれ` to_string() ` と` String::from ` を使って、
61
+ 所有権のある` String ` 型に変換しなければならない点に注意してください。
41
62
63
+ <!--
42
64
## A more efficient approach
65
+ -->
66
+ ## より効率的なやり方
43
67
68
+ <!--
44
69
Here we pass ownership of the open `File` to a `BufReader` struct. `BufReader` uses an internal
45
70
buffer to reduce intermediate allocations.
71
+ -->
72
+ ここでは、開いた` File ` の所有権を` BufReader ` 構造体に渡します。
73
+ ` BufReader ` は内部的なバッファを使い、中間のメモリ割り当てを削減します。
46
74
75
+ <!--
47
76
We also update `read_lines` to return an iterator instead of allocating new
48
77
`String` objects in memory for each line.
78
+ -->
79
+ ` read_lines ` を更新して、それぞれの行に対してメモリ上に新しい` String ` オブジェクトを割り当てるのではなく、イテレータを返すようにします。
49
80
50
81
``` rust,no_run
51
82
use std::fs::File;
@@ -54,8 +85,10 @@ use std::path::Path;
54
85
55
86
fn main() {
56
87
// File hosts.txt must exist in the current path
88
+ // hosts.txtファイルは現在のパスに存在しなければならない。
57
89
if let Ok(lines) = read_lines("./hosts.txt") {
58
90
// Consumes the iterator, returns an (Optional) String
91
+ // イテレータを消費し、Option型のStringを返す。
59
92
for line in lines {
60
93
if let Ok(ip) = line {
61
94
println!("{}", ip);
@@ -66,24 +99,37 @@ fn main() {
66
99
67
100
// The output is wrapped in a Result to allow matching on errors
68
101
// Returns an Iterator to the Reader of the lines of the file.
102
+ // 出力はResult型にラップされ、エラーをマッチできるようになる。
103
+ // ファイルの各行のReaderへのイテレータを返す。
69
104
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
70
105
where P: AsRef<Path>, {
71
106
let file = File::open(filename)?;
72
107
Ok(io::BufReader::new(file).lines())
73
108
}
74
109
```
75
110
111
+ <!--
76
112
Running this program simply prints the lines individually.
113
+ -->
114
+ このプログラムを実行すると、単に各行をプリントします。
115
+
77
116
``` shell
78
117
$ echo -e " 127.0.0.1\n192.168.0.1\n" > hosts.txt
79
118
$ rustc read_lines.rs && ./read_lines
80
119
127.0.0.1
81
120
192.168.0.1
82
121
```
83
122
123
+ <!--
84
124
(Note that since `File::open` expects a generic `AsRef<Path>` as argument, we define our
85
125
generic `read_lines()` method with the same generic constraint, using the `where` keyword.)
126
+ -->
127
+ ` File::open ` はジェネリックな` AsRef<Path> ` を引数にとるので、
128
+ ジェネリックな` read_lines ` メソッドも、` where ` キーワードを使って、同じジェネリックな制約を持たせています。
86
129
130
+ <!--
87
131
This process is more efficient than creating a `String` in memory with all of the file's
88
132
contents. This can especially cause performance issues when working with larger files.
89
-
133
+ -->
134
+ この処理は、ファイルの中身全てをメモリ上の` String ` にするよりも効率的です。
135
+ メモリ上に` String ` を作ると、より大きなファイルを取り扱う際に、パフォーマンスの問題につながります。
0 commit comments