您在Rust中无法做的事情:关闭复制

我爱Rust,希望它变得更好。 开发团队知道所有提出的问题。 我只是想引起大家的讨论和热情,以使一种好的语言变得更好。

fn main() {
// Many closures can now be passed by-value to multiple functions:
fn call<F: FnOnce()>(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<F: FnMut()>(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<std::ops::Range<{integer}>, [closure@a.ru:9:24: 9:33]>`
 error: aborting due to previous error(s) 

公平地说,此功能已部分实现。 要实现Copy,编译器需要注意生存期和可变性,因此这不是一个简单的功能。 到目前为止,已经涵盖了许多常见情况,但是如RFC(2132)示例所示,还有很长的路要走。 目前,这是对关闭的另一个警告。

From: https://hackernoon.com/things-you-cant-do-in-rust-copy-closures-79d2c0586da

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值