gpt4 book ai didi

generics - 实现拥有和借用的特征

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

这个问题在这里已经有了答案:





Do I have to implement a trait twice when implementing it for both reference and non-reference types?

(3 个回答)


2年前关闭。




我有以下使用rust 片段:

trait Foo { 
fn foo(&self);
}

struct FooImpl;

impl Foo for FooImpl {
fn foo(&self) {}
}

fn do_foo(foo_doer: impl Foo) {
foo_doer.foo()
}
这条线有效:
do_foo(FooImpl {});
但是当我尝试运行它时:
do_foo(&FooImpl {});
我可以理解得到错误: the trait bound &FooImpl: Foo is not satisfied .
我显然可以这样做:
impl Foo for &FooImpl { fn foo(&self) {} }
然后它会起作用,但是我必须为多种类型执行此操作,并且每次都必须复制一些代码。此外,在我的情况下,我不仅可以获得借用,还可以获得可变借用。这意味着我必须为 &mut FooImpl 实现它,有时我想从可变借用的不可变借用中运行它,这意味着我必须为 &&mut FooImpl 实现它,你明白了。
我的问题是,您是否可以推荐一些 trait impl/generic 技巧来允许我为拥有的实例和借用的实例实现 trait?
或者,我可以在 do_foo 上更改一些内容吗?允许它接受这两种类型的实例的功能端?
我已阅读 Do I have to implement a trait twice when implementing it for both reference and non-reference types?它适用于我的玩具程序。但我的问题是我试图在我的实际代码中实现的特征来自不同的 crate ,所以编译器不允许我实现 Borrow<FooImpl>由于孤儿规则,我认为该特征(错误: type parameter B must be used as the type parameter for some local type)。是否有解决孤儿规则的解决方案?

最佳答案

My question is whether there is some trait impl / generic trickery you can recommend that will allow me to impl a trait for both owned instances and borrowed instances?



您也许可以 use Borrow/AsRef .

sometimes I'd like to run it from an immutable borrow of the mutable borrow meaning I have to implement it for &&mut FooImpl, you get the idea.



只需重新借入即可获得 &FooImpl ?

关于generics - 实现拥有和借用的特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61728886/

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