rust命令复制不了怎么办
我爱Rust,希望它变得更好。 开发团队知道所有提出的问题。 我只想引起讨论和热情,以使一种更好的语言变得更好。
fn main() {
// Many closures can now be passed by-value to multiple functions:
fn call(f: F) { f() }
let hello = || println!("Hello, world!");
call(hello);
call(hello);
// Many `Iterator` combinators are now `Copy`/`Clone`:
let x = (1..100).map(|x| x * 5);
let y = x.map(|x| x - 3); // moves `x` by `Copy`ing
let _ = x.chain(y); // moves `x` again
let _ = x.cycle(); // `.cycle()` is only possible when `Self: Clone`
// Closures which reference data mutably are not `Copy`/`Clone`:
let mut x = 0;
let incr_x = || x += 1;
call(incr_x);
call(incr_x); // ERROR: `incr_x` moved in the call above.
// `move` closures implement `Clone`/`Copy` if the values they capture
// implement `Clone`/`Copy`:
let mut x = 0;
let print_incr = move || { println!("{}", x); x += 1; };
fn call_three_times(mut f: F) {
for i in 0..3 {
f();
}
}
call_three_times(print_incr); // prints "0", "1", "2"
call_three_times(print_incr); // prints "0", "1", "2"
}
结果(编译时错误):
error[E0277]: the trait bound `[closure@a.ru:9:24: 9:33]: std::clone::Clone` is not satisfied
|
12 | let _ = x.cycle(); // `.cycle()` is only possible when `Self: Clone`
| ^^^^^ the trait `std::clone::Clone` is not implemented for `[closure@a.ru:9:24: 9:33]`
|
= note : required because of the requirements on the impl of `std::clone::Clone` for `std::iter::Map, [closure@a.ru:9:24: 9:33]>`
error: aborting due to previous error(s)
公平地说,此功能已部分实现。 要实现Copy,编译器需要注意生存期和可变性,因此这不是一个简单的功能。 到目前为止,已经涵盖了许多常见情况,但是如RFC(2132)示例所示,还有很长的路要走。 就目前而言,这是对关闭的另一个警告。
翻译自: https://hackernoon.com/things-you-cant-do-in-rust-copy-closures-79d2c0586da
rust命令复制不了怎么办