标签:explain run span more cte long nis func --
fn consume_with_relish<F>(mut func: F) where F: FnMut() -> String { // `func` consumes its captured variables, so it cannot be run more // than once println!("Consumed 1 "); func(); println!("Consumed 2"); func(); println!("Delicious!"); // Attempting to invoke `func()` again will throw a `use of moved // value` error for `func` } fn main() { let mut x = String::from("x"); let consume_and_return_x = move || { x.push(‘*‘); println!("x {}", x); }; consume_with_relish(consume_and_return_x); // `consume_and_return_x` can no longer be invoked at this point }
cargo build Compiling hello_world v0.1.0 (/data2/rust/FnMut) error[E0271]: type mismatch resolving `<[closure@src/main.rs:17:32: 20:3 x:_] as std::ops::FnOnce<()>>::Output == std::string::String` --> src/main.rs:21:5 | 1 | fn consume_with_relish<F>(mut func: F) where F: FnMut() -> String | ------ required by this bound in `consume_with_relish` ... 21 | consume_with_relish(consume_and_return_x); | ^^^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found `()` error: aborting due to previous error For more information about this error, try `rustc --explain E0271`. error: could not compile `hello_world`. To learn more, run the command again with --verbose.
原来 FnMut 没返回值
pub trait FnMut<Args>: FnOnce<Args> { extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output; }
[root@bogon FnMut]# cargo build Compiling hello_world v0.1.0 (/data2/rust/FnMut) Finished dev [unoptimized + debuginfo] target(s) in 0.43s [root@bogon FnMut]# cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.01s Running `target/debug/hello_world` Consumed 1 x x* Consumed 2 x x** Delicious! [root@bogon FnMut]# cat src/main.rs fn consume_with_relish<F>(mut func: F) where F: FnMut() { // `func` consumes its captured variables, so it cannot be run more // than once println!("Consumed 1 "); func(); println!("Consumed 2"); func(); println!("Delicious!"); // Attempting to invoke `func()` again will throw a `use of moved // value` error for `func` } fn main() { let mut x = String::from("x"); let consume_and_return_x = move || { x.push(‘*‘); println!("x {}", x); }; consume_with_relish(consume_and_return_x); // `consume_and_return_x` can no longer be invoked at this point } [root@bogon FnMut]#
标签:explain run span more cte long nis func --
原文地址:https://www.cnblogs.com/dream397/p/14206932.html