在结构体中声明闭包时定义使用冲突
我正在尝试创建一个包含多个可复制闭包的结构。
type ClosureType = impl Fn(u64) -> u64 + Clone;
fn closure_try(t: u64) -> ClosureType {
move |x: u64| x + t
}
fn closure_try_other(u: u64) -> ClosureType {
move |x: u64| x - u
}
#[derive(Clone)]
pub struct Wrapper {
pub h: Vec<ClosureType>
}
trait Tr: Clone {
fn dup(s: Self) -> (Self, Self);
}
impl Tr for Wrapper {
fn dup(c: Self) -> (Self, Self) {
(c.clone(), c)
}
}
但是,此代码失败并出现 ClosureType
错误:
rustc: concrete type differs from previous defining opaque type use
这是否意味着此方法不能用于存储多个不同的闭包?
I'm trying to create a struct that holds multiple copyable closures.
type ClosureType = impl Fn(u64) -> u64 + Clone;
fn closure_try(t: u64) -> ClosureType {
move |x: u64| x + t
}
fn closure_try_other(u: u64) -> ClosureType {
move |x: u64| x - u
}
#[derive(Clone)]
pub struct Wrapper {
pub h: Vec<ClosureType>
}
trait Tr: Clone {
fn dup(s: Self) -> (Self, Self);
}
impl Tr for Wrapper {
fn dup(c: Self) -> (Self, Self) {
(c.clone(), c)
}
}
However this code fails with the error for ClosureType
:
rustc: concrete type differs from previous defining opaque type use
Does it mean that this approach cannot be used to store multiple different closures?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
type t = Impl特征
只是命名不透明类型的一种方法。它是存在类型,这意味着它具有一个和仅一个具体的定义。colletype
是某种不愿意的类型,但由于相同的原因,它不能是两种不同的类型类型-can-impl-trait-not-be-be-be-return-multiph-multiph-conditional-types'>您无法从返回Impl特征
的函数中返回两种不同类型。如果您需要多种类型的
vec
,即异质集合,则必须使用动态分配,即dyn特征
。type T = impl Trait
is only a way to name the opaque type. It is an existential type, meaning it has one and only one concrete definition.ClosureType
is some unnamable type, but it cannot be two distinct types, for the same reason you cannot return two different types from a function that returnsimpl Trait
.If you need multiple types for the
Vec
, i.e. a heterogeneous collection, you have to use dynamic dispath, i.e.dyn Trait
.