本文介绍了为什么会出现错误“& mut T"未实现特征'Foo'?即使T实现了特质?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个来源:

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,但是错误却相反.

The only aspect of C that is defined is that it implements CharacterCache, yet the error says the opposite.

DrawStateMatrix2dCharacterCache及其实现,Texture和self.properties(Text)由Piston 2d图形库提供.一般来说,关于特质的某些事情我会误会.

DrawState, Matrix2d, CharacterCache and its implementations, Texture, and self.properties (Text) are provided by the Piston 2d graphics library. There must be something about traits in general that I'm misunderstanding.

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同样是不同的类型.不会自动实现对类型的引用的特性.如果您希望为任何一个引用实现特征,则需要将其显式写出.

T, &T, and &mut T are all different types; and that means that &mut &mut T is likewise a different type. Traits are not automatically implemented for references to a type. If you wish to implement a trait for either of the references, you need to write it out explicitly.

作为一个例子,它表现出相同的问题:

As an example, this exhibits the same problem:

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
}

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

Explicit implementations of the trait for the references solve the problem:

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

在许多情况下,您可以将函数实现委派给非引用实现.

In many cases, you can delegate the function implementations to the non-reference implementation.

如果应该始终为真,则可以通过将其应用于实现特征的类型的 all 引用来实现:

If this should always be true, you can make it so by applying it to all references to a type that implements a trait:

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

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

If you don't have control over the traits, you may need to specify that you take a reference to a generic type that implements the trait:

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

另请参阅:

这篇关于为什么会出现错误“&amp; mut T"未实现特征'Foo'?即使T实现了特质?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:58