Warning
This post was published 70 days ago. The information described in this article may have changed.
The following works fine:
struct MyFields {
field: i32
}
trait MyTrait{
fn get_field(&self)->i32;
fn manipulate_field(&self)->i32;
}
impl MyTrait for MyFields {
fn get_field(&self)->i32{
self.field
}
fn manipulate_field(&self) ->i32 {
self.get_field() +100
}
}
But it feels kind of verbose. I don't really want to have to define a getter for my trait, I just want to be able to create a fn called manipulate_field
with a trait bound that says the struct it's defined on has a field called field
(with type i32
), and then I'd only need one function in my trait and I could just use self.field
directly.
Does this exist? If not, why not?
In my actual use case, I have a field that is a HashMap, so I'd actually want to put trait bounds on the fields in the struct in the trait definition, is this sensible?
Maybe the answer is that the best way to indirectly put trait bounds on the fields in a struct is to specify what getters are available, but I wanted to make sure I wasn't missing a language feature...
4 posts - 3 participants
🏷️ rust_feed