【发布时间】:2021-12-30 08:24:41
【问题描述】:
在我的项目中,我使用类型定义来保存具有特定函数签名的闭包,如下所示:
// Standardized function signature
pub type InternalOperation = impl Fn(Ast, Rc<RefCell<VTable>>, Rc<RefCell<FTable>>) -> Ctr;
pub struct ExternalOperation {
// ...
// The project is on gitlab called relish if you are interested
}
/* A stored function may either be a pointer to a function
* or a syntax tree to eval with the arguments
*/
pub enum Operation {
Internal(InternalOperation),
External(ExternalOperation)
}
// function which does not need args checked
pub struct Function {
pub function: Operation,
// many more things like argument types and function name
}
我尝试实例化一个函数:
pub fn get_export(env_cfg: bool) -> Function {
return Function{
name: String::from("export"),
loose_syms: true,
eval_lazy: true,
args: Args::Lazy(2),
function: Operation::Internal(
|a: Ast, b: Rc<RefCell<VTable>>, c: Rc<RefCell<FTable>>| -> Ctr {
// so much logic here to manage variables in b
// if env_cfg is true, entries in b are tied to environment variables
})
}
}
但随后我收到以下错误:
error[E0308]: mismatched types
--> src/vars.rs:49:13
|
49 | / |a: Ast, b: Rc<RefCell<VTable>>, c: Rc<RefCell<FTable>>| -> Ctr {
50 | | let inner = a.borrow_mut();
51 | | match &inner.car {
52 | | Ctr::Symbol(identifier) => {
... |
96 | | return Ctr::None;
97 | | }
| |_____________^ expected opaque type, found closure
|
我尝试过的:
- 将 InternalOperation 声明为匿名函数。这可行,但我无法存储闭包。
- 我尝试使用 InternalOperation(......) 声明闭包,根据语法规则这是不正确的
我在这里使用闭包,以便我的应用程序的用户配置可以在函数操作的主体中使用。是否可以以这种方式使用闭包,还是需要重构我的代码以以其他方式应用 env_cfg 值?
【问题讨论】:
-
在类型别名中使用
impl Trait是不稳定的。你开启type_alias_impl_trait的功能了吗?