2
pub struct Entity {
    name: String,
}

fn walk<T>(entity: T) {
    eprintln!("{} walked", entity.name);
}

Currently the following code doesn't compile, because the type T doesn't have a name field.
I know there are trait bounds in rust, is there some "field bound"?

Do i really have to:

trait HasName {}
impl HasName for Entity {}
fn walk<T: HasName>(entity: T) {
    eprintln!("{}", entity.name);
}

Oh wait, that too won't compile!
Here's a working example

I mean, there's got to be something simpler than that.
Maybe some kind of struct destructuring like in javascript?

Soft Waffle
  • 356
  • 1
  • 12
  • 1
    Does this answer your question? [Is it possible to access struct fields from within a trait?](https://stackoverflow.com/questions/28219730/is-it-possible-to-access-struct-fields-from-within-a-trait) – joel May 03 '20 at 21:52
  • @joelb i must inform you that i already marked a present answer as solved and i no longer need an answer, but thanks – Soft Waffle May 03 '20 at 22:09
  • 1
    ok Paul. When a comment starting as mine does appears, it's cos I've suggested to stack overflow that this question is a duplicate. Depending on review, it may be closed – joel May 03 '20 at 22:16

1 Answers1

5

Currently you cannot have associated fields in traits, see this RFC.

However you can add a function to the trait, just like in the example you have linked. However, you can elide the lifetimes:

pub trait HasName {
    fn name(&self) -> &str;
}

impl HasName for Entity {
    fn name(&self) -> &str {
        &self.name
    }
}
  • 1
    I've read that RFC and it still requires a trait impl, i just need something like [this](https://www.reddit.com/r/rust/comments/gcz5i0/generics_to_check_for_struct_fields_presence/). sorry if you can't understand it, i vowed to go to sleep at 21:00 this time and look at me now (i didn't, now i'm sleepy) – Soft Waffle May 03 '20 at 22:05
  • 1
    Use a macro. Or better yet, don't do that. Traits is what Rust uses for genericity, they're not structural, and as parent notes they don't support associated fields. – Masklinn May 04 '20 at 05:42