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/47743955/

相关文章:

rust - 如何从更高级别的特征绑定(bind)特征返回关联类型?

rust - 通过取消引用来延长对象的生命周期

scala - 如何在 scala 的泛型方法中创建特征的实例?

generics - 有没有办法在 Rust 中模拟通用关联类型/关联类型构造函数?

具有关联类型的 Swift 子协议(protocol)

rust - 递归探索多维向量

macros - 宏中 `use` 的正确方法

rust - 什么使某些东西成为 "trait object"?

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

string - 如何从 Rust 中的字符串开头删除 "crop"个字符?