[英]What is the idiomatic way in rust for a function accepts a closure as argument or return a closure?
[英]Return a closure returning the function argument in Rust
我正在嘗試編寫一個函數,該函數將采用 T 類型的參數並返回一個閉包,該閉包在調用時將返回該參數。 我該怎么寫?
pub struct ParseError {}
pub type Parser<T> = Box<dyn Fn(&str) -> Result<(&str, T), ParseError>>;
pub fn pure<T: 'static>(value: T) -> Parser<T> {
Box::new(move |input: &str| -> Result<(&str, T), ParseError> { Ok((input, value)) })
}
錯誤:
Checking parsec v0.1.0 (/home/arjaz/Documents/code/rust/parsec)
error[E0507]: cannot move out of `value`, a captured variable in an `Fn` closure
--> src/parsec.rs:16:79
|
12 | pub fn pure<T: 'static>(value: T) -> Parser<T>
| ----- captured outer variable
...
16 | Box::new(move |input: &str| -> Result<(&str, T), ParseError> { Ok((input, value)) })
| ^^^^^ move occurs because `value` has type `T`, which does not implement the `Copy` trait
error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
error: could not compile `parsec`.
這是Rust playground 中的一個簡化版本,它避免了 Box 和 Parser。 該函數消耗value
,並返回一個閉包,當調用時,它只返回value
。 請注意,閉包是FnOnce
類型(或者更准確地說,是基於FnOnce
的某種類型),因此我們只能調用它一次。 調用后,與value
關聯的內存屬於調用者。
相反,如果我們使用Fn
,則可以多次調用閉包。 但是在第一次調用之后,閉包不再擁有value
——它作為返回值提供給第一個調用者——所以第二次調用閉包是行不通的。 因此錯誤。 如果一個閉包要多次返回該值,那么它必須返回一個value
的副本或克隆,為自己保留原始的所有權。 由於該函數對value
的類型T
是通用的,因此您需要將T
約束為Copy
或Clone
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.