FnOnce <RUST>


#[lang = "fn_once"] #[must_use = "closures are lazy and do nothing unless called"] pub trait FnOnce<Args> { type Output; extern "rust-call" fn call_once(self, args: Args) -> Self::Output; }

The version of the call operator that takes a by-value receiver.

Instance of FnOnce can be called, but might not be callable multiple times. Because of this, if the only thing known about a type is that it implements FnOnce, it can only be called once.

FnOnce is implemented automatically by closure that might consumer captured variable, as well as all types that implement FnMut, e.g(safe)function pointer (since FnOnce is a supertrait of FnMut).

Since both Fn and FnMut are subtraits of FnOnce, any instance of Fn or FnMut can be used where a FnOnce is expected.

Use FnOnce as a bound when you want to accept a parameter of function-like type and only need to call it once. If you need to call the parameter repeatedly, use FnMut as a bound; if you also need it to not mutate state, use Fn.

Aslo of note is the sapcial syntax for Fn traits(e.g Fn(usize, bool) -> usize). Those interested in the technical details of this can refer to the relevant section in the Rustonmicon.

 1 fn consume_with_relish<F>(func: F) 
 2     where F: FnOnce() -> String
 3 {
 4     // 'func' consumers it captured variables, so it cannot be run more than once.
 5     println!("Consumed: {}", func());
 6     
 7     println!("Delicious!");
 8 
 9     //Attempting to invoke 'func()' again will therow a 'use of moved 
10     // value 'error for 'func'
11 }
12 
13 let x = String::from("x");
14 let consume_and_return_x = move || x;
15 consume_with_relish(consume_and_return_x);

猜你喜欢

转载自www.cnblogs.com/Davirain/p/13373683.html