1

Image we have a code as given below:

trait MyTrait {
    fn foo(&mut self) {
        // self.0 += 1;
    }
}

struct S1(usize);
impl MyTrait for S1 {}

struct S2(usize);
impl MyTrait for S2 {}

fn main() {
    let mut s = S1(0);
    s.foo();
    let mut s = S2(0);
    s.foo();
}

Is there a way to tell the compiler that the trait method foo expects its parameter to have only one argument with the usize type?

109149
  • 1,223
  • 1
  • 8
  • 24
  • 1
    Do the answers to [Is it possible to access struct fields from within a trait?](/q/28219730/3650362) answer your question? If not, please [edit] your question to explain the differences. – trent Oct 18 '20 at 19:10
  • 1
    I think a lot of the time when people ask for a feature like this, what they really want is a [generic struct specialized with different types](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e6ada32367ff9d36386473f8e3c8bb7a). I have never really seen a good justification for "fields in traits". – trent Oct 18 '20 at 19:15
  • 1
    @trentcl Thank you, [this answers](https://stackoverflow.com/a/48470287/14414945) my question. – 109149 Oct 18 '20 at 19:17

0 Answers0