@@ -131,6 +131,59 @@ fn main() {
131
131
}
132
132
```
133
133
134
+ <!-- As closures can capture variables from their environment, we can also try to -->
135
+ <!-- bring some data into the other thread: -->
136
+ クロージャは環境から変数を捕捉出来るので、スレッドにデータを取り込もうとすることも出来ます。
137
+
138
+
139
+ ``` rust,ignore
140
+ use std::thread;
141
+
142
+ fn main() {
143
+ let x = 1;
144
+ thread::spawn(|| {
145
+ println!("x is {}", x);
146
+ });
147
+ }
148
+ ```
149
+
150
+ <!-- However, this gives us an error: -->
151
+ しかし、これはエラーです。
152
+
153
+ ``` text
154
+ 5:19: 7:6 error: closure may outlive the current function, but it
155
+ borrows `x`, which is owned by the current function
156
+ ...
157
+ 5:19: 7:6 help: to force the closure to take ownership of `x` (and any other referenced variables),
158
+ use the `move` keyword, as shown:
159
+ thread::spawn(move || {
160
+ println!("x is {}", x);
161
+ });
162
+ ```
163
+
164
+ <!-- This is because by default closures capture variables by reference, and thus the -->
165
+ <!-- closure only captures a _reference to `x`_. This is a problem, because the -->
166
+ <!-- thread may outlive the scope of `x`, leading to a dangling pointer. -->
167
+ これはクロージャはデフォルトで変数を参照で捕捉するためクロージャは _ ` x ` への参照_ のみを捕捉するからです。
168
+ これは問題です。なぜならスレッドは ` x ` のスコープよに長生きするかもしれないのでダングリングポインタを招きかねません。
169
+
170
+ <!-- To fix this, we use a `move` closure as mentioned in the error message. `move` -->
171
+ <!-- closures are explained in depth [here](closures.html#move-closures); basically -->
172
+ <!-- they move variables from their environment into themselves. -->
173
+ これを直すにはエラーメッセージにあるように ` move ` クロージャを使います。
174
+ ` move ` クロージャは [ こちら] ( closures.html#move-closures ) で詳細に説明されていますが、基本的には変数を環境からクロージャへムーブします。
175
+
176
+ ``` rust
177
+ use std :: thread;
178
+
179
+ fn main () {
180
+ let x = 1 ;
181
+ thread :: spawn (move || {
182
+ println! (" x is {}" , x );
183
+ });
184
+ }
185
+ ```
186
+
134
187
<!-- Many languages have the ability to execute threads, but it's wildly unsafe. -->
135
188
<!-- There are entire books about how to prevent errors that occur from shared -->
136
189
<!-- mutable state. Rust helps out with its type system here as well, by preventing -->
0 commit comments