Use `&self` in trait

Hello guys! This is a part of my code at the moment:

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Pipeline {
    prefetch: Prefetch,
    decoded_instruction: Option<Box<dyn Instruction>>,
}

pub trait Instruction {
    fn execute(&self);

    fn get_address(&self) -> Address;
}

and I'm getting the following hints from rust-analyzer:

Diagnostics:
1. `(dyn Instruction + 'static)` doesn't implement `Debug`
   the trait `Debug` is not implemented for `(dyn Instruction + 'static)`
2. the trait bound `dyn Instruction: Clone` is not satisfied
   required because of the requirements on the impl of `Clone` for `Box<dyn Instruction>`
   1 redundant requirement hidden
   required because of the requirements on the impl of `Clone` for `Option<Box<dyn Instruction>>`
3. binary operation `==` cannot be applied to type `Option<Box<dyn Instruction>>`
4. binary operation `!=` cannot be applied to type `Option<Box<dyn Instruction>>`
5. the trait bound `dyn Instruction: std::cmp::Eq` is not satisfied
   required because of the requirements on the impl of `std::cmp::Eq` for `Box<dyn Instruction>`
   1 redundant requirement hidden
   required because of the requirements on the impl of `std::cmp::Eq` for `Option<Box<dyn Instruction>>`

rust-analyzer also says, that I'm using &self in the Instruction trait. Is that not okay or why is it showing me this?

I'm a little bit overhelmed by this. The trait looks fine for me and I can't find the problem on the rust-reference. What am I doing wrong?

First, always inspect the errors from the terminal by cargo invocation. The compiler does a great job emitting good and useful error messages, and rust-analyzer many times mess them up :frowning:

For your code, the problem is that, well, dyn Instruction doesn't implement any of those traits (Debug, Clone, PartialEq, Eq or Default), and it's required for you to be able to derive them on it.

3 Likes