gpt4 book ai didi

rust - 基于类型参数选择了错误的特征

转载 作者:行者123 更新时间:2023-11-29 07:56:50 25 4
gpt4 key购买 nike

我有一个二进制特征 Resolve

pub trait Resolve<RHS = Self> {
type Output;
fn resolve(self, rhs: RHS) -> Self::Output;
}

我为一些微不足道的事情实现了这个特征,其中两个参数都是通过引用获取的(self&'a Foorhs&'b Foo):

struct Foo;

impl <'a, 'b> Resolve<&'b Foo> for &'a Foo {
type Output = Foo;
fn resolve(self, rhs: &'b Foo) -> Self::Output {
unimplemented!()
}
}

如果我现在写

fn main() {
let a: &Foo = &Foo;
let b = Foo;
a.resolve(&b);
}

它会编译得很好,但如果我尝试在我的结构 Signal 上实现它,它将无法工作。

pub struct Signal<'a, T> {
ps: Vec<&'a T>,
}

impl<'a, T: Resolve<&'a T, Output = T> + 'a> Signal<'a, T> {
pub fn foo(&mut self) {
let a: &T = &self.ps[0];
let b = &self.ps[1];
a.resolve(b);
}
}
error[E0507]: cannot move out of borrowed content
--> src/main.rs:25:9
|
25 | a.resolve(b);
| ^ cannot move out of borrowed content

如何让这个示例工作? ( playground )

最佳答案

foo 上的 trait bound 只说明 T 实现了 Resolve,但是你尝试调用 .resolve() 在类型 &T 的值上。

相反,T 的引用 必须实现 Resolve,您需要 higher-ranked trait bound :

impl<'a, T> Signal<'a, T>
where
for<'b> &'b T: Resolve<&'a T, Output = T>,
{
pub fn foo(&mut self) { ... }
}

关于rust - 基于类型参数选择了错误的特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53125347/

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