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

标签 rust traits associated-types

我有这个来源:

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/

相关文章:

rust - 无法为实现我拥有的特征的所有类型实现我不拥有的特征

ios - 关联类型为类的协议(protocol)的扩展?

ios - Swift:使用泛型类型的实例关联类型段错误编译器

struct - 同时改变多个结构字段的最快惯用方法是什么?

rust - 如何安装命令 "cargo set-version"?

rust - 在 trait 中定义一个返回 Self 的默认实现的方法

scala - 可堆叠特征模式可以与单例对象一起使用吗?

ios - 如何在我的协议(protocol)中正确使用 associatedType

rust - cargo build --release 的默认优化级别是多少?

rust - 如何阻止 `cargo clippy` 运行依赖项?