0

I have a snake game with 2 types of food:

The Fly:

 struct Fly {
    x: u32,
    y: u32,
}

And the Spider, which disappears if not eaten in time:

struct Spider {
    x: u32,
    y: u32,
    ticks_alive: i32,
}

I want them to have some convenient methods like position(&self) -> (u32, u32) or proxy() -> SpiderOrFly:

pub trait Food<Type> {
    fn position(&self) -> (u32, u32) {
        (self.x, self.y)
    }

    fn proxy() -> Type {
        Type { x: 0, y: 0 }
    }
}

I'm getting errors that x is not a field of &self and that Type is not a struct

Is there a way to tell Rust that Type has to be Fly or Spider so that I can access the instance variables in the generic implementation and don't have to produce doubled code?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
KuSpa
  • 325
  • 4
  • 14
  • You can't use `self.x` and `self.y` inside the default trait implementation, because some implementation of the trait _might_ not have those fields. – Peter Hall May 12 '18 at 17:18
  • I believe your question is answered by the answers of [Is it possible to access struct fields from within a trait?](https://stackoverflow.com/q/28219730/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster May 12 '18 at 17:18
  • The other problem is that you are trying to use `Type` as a constructor, but the compiler can't know what the constructor looks like for every possible concrete type there. In fact, even if that was allowed, your code would break for `Spider` because `ticks_alive` is missing. – Peter Hall May 12 '18 at 17:25

0 Answers0