gpt4 book ai didi

rust - 如何创建一个实现 Fn 并可以克隆到不同对象的特征对象?

转载 作者:行者123 更新时间:2023-12-03 11:28:28 27 4
gpt4 key购买 nike

<分区>

如果我想要一个不可复制的类型删除(动态类型)可调用,那就是

Box<dyn Fn(i32) -> ()>

如果我想要一个引用计数类型删除的可调用对象,那是(取决于我是否需要线程安全)

Rc<dyn Fn(i32) -> ()>
Arc<dyn Fn(i32) -> ()>

但在这里,副本都引用相同的底层内存 - 它们并不不同。

如果我想要 distinct 可调用对象,我该怎么做? Box<T>已经实现 Clone什么时候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 创建类型对象?是可克隆的,副本是不同的?

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com