如果我需要一个不可拷贝的类型擦除(动态类型)可调用对象,那么
如果我需要一个引用计数的类型擦除可调用对象,那么(取决于是否需要线程安全)
错误信息中的建议由于
有没有一种创建可克隆的类型对象
Box<dyn Fn(i32) -> ()>
如果我需要一个引用计数的类型擦除可调用对象,那么(取决于是否需要线程安全)
Rc<dyn Fn(i32) -> ()>
Arc<dyn Fn(i32) -> ()>
然而,在这里,所有的副本都指向同一个底层内存 - 它们不是独立的。
如果我想要独立的可调用对象,该怎么办?Box<T>
已经在 T
实现了 Clone
,但是 Fn
没有实现 Clone
,所以这个方法并不适用。做一些像这样的事情:
Box<dyn Fn(i32) -> () + Clone>
出现错误:
error[E0225]: only auto traits can be used as additional traits in a trait object
--> src/main.rs:7:35
|
7 | fn foo(f: Box<dyn Fn(i32) -> () + Clone>) {
| ------------- ^^^^^ additional non-auto trait
| |
| first non-auto trait
|
= help: consider creating a new trait with all of these as super-traits and using that trait here instead: `trait NewTrait: Fn<(i32,)> + Clone {}`
= note: auto-traits like `Send` and `Sync` are traits that have special properties; for more information on them, visit <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>
错误信息中的建议由于
Fn
拼写错误而无法工作,但这个方法可以:trait CopyableFn: Fn(i32) -> () + Clone {}
Box<dyn CopyableFn>
仅仅只有这个还不行,因为:
error[E0038]: the trait `CopyableFn` cannot be made into an object
--> src/main.rs:7:11
|
5 | trait CopyableFn: Fn(i32) -> () + Clone {}
| ---------- ----- ...because it requires `Self: Sized`
| |
| this trait cannot be made into an object...
6 |
7 | fn foo(f: Box<dyn CopyableFn>) {
| ^^^^^^^^^^^^^^^^^^^ the trait `CopyableFn` cannot be made into an object
有没有一种创建可克隆的类型对象
Fn
并使得副本是不同的方法?
Clone
添加为CopyableFn
的超特质会使其不再是对象安全的(dyn CopyableFn
就无效了)。那个答案中解释的解决方案 (clone_box
) 将可以解决你的问题。 - Ibraheem AhmedFn
没有实现Clone
吗? [你确定吗?] - Shepmaster