gpt4 book ai didi

rust - 为什么我会收到错误 "the trait ` Foo` is not implemented for `&mut T` “即使 T 实现了特征?

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

我有这个来源:

pub fn draw<G, C>(&self, font: &mut C, draw_state: &DrawState, transform: Matrix2d, g: &mut G)
where
C: CharacterCache,
G: Graphics<Texture = <C as CharacterCache>::Texture>,
{
self.properties.draw(
self.text.as_str(),
&mut font,
&draw_state,
transform,
g,
);
}

错误

the trait bound `&mut C: graphics::character::CharacterCache` is not satisfied 
(the trait `graphics::character::CharacterCache` is not implemented for `&mut C`)

定义的 C 的唯一方面是它实现了 CharacterCache,但错误却恰恰相反。

DrawStateMatrix2dCharacterCache 及其实现、Texture 和 self.properties( Text) 由 Piston 2d 图形库提供。总的来说,一定有一些我误解了的特质。

Text::draw 函数签名:

fn draw<C, G>(
&self,
text: &str,
cache: &mut C,
draw_state: &DrawState,
transform: Matrix2d,
g: &mut G,
) where
C: CharacterCache,
G: Graphics<Texture = C::Texture>,

最佳答案

T&T&mut T 都是不同类型;这意味着 &mut &mut T 同样是不同的类型。不会为对类型的引用自动实现特征。如果您希望为任一引用实现特征,则需要明确地将其写出来。

例如,这表现出同样的问题:

trait Foo {}

#[derive(Debug, Copy, Clone)]
struct S;
impl Foo for S {}

fn example<T>(_: T)
where
T: Foo,
{}

fn main() {
let mut s = S;

example(s);
example(&s); // the trait bound `&S: Foo` is not satisfied
example(&mut s); // the trait bound `&mut S: Foo` is not satisfied
}

引用的特征的显式实现解决了这个问题:

impl<'a> Foo for &'a S {}
impl<'a> Foo for &'a mut S {}

在许多情况下,您可以将函数实现委托(delegate)给非引用实现。

如果这应该始终为真,您可以通过将其应用于所有 对实现特征的类型的引用来实现:

impl<'a, T> Foo for &'a T where T: Foo {}
impl<'a, T> Foo for &'a mut T where T: Foo {}

如果您无法控制特征,您可能需要指定您引用了实现该特征的泛型类型:

fn example<T>(_: &mut T)
where
for<'a> &'a mut T: Foo,
{}

另见:

关于rust - 为什么我会收到错误 "the trait ` Foo` is not implemented for `&mut T` “即使 T 实现了特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44928882/

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