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...
No, there's no structural typing in Rust, and neither is there compile-time reflection. The former is just not the way Rust works, and the latter because nobody has yet designed, advocated for, and implemented a huge complex feature.
Thanks for the reply. I'm guessing then that the answer is that defining getters in the trait (or in another trait that I can then bound my methods with) is the best solution currently? I don't know what some those terms mean, would you mind explaining?
What does structural typing mean in the context of my example? Is that having the type system be aware of struct's fields and types?
What is compile-time reflection in the context of my example? My hazy understanding of reflection is it's got something to do with what the compiler "knows" about the objects it's working with, but I don't know more than that...
It’s also possible that a trait is the wrong tool for what you want. Another option would be defining methods on a generic struct
that has the fields you care about in the non-generic portion.
4 Likes
What do you mean by the "non-generic portion"? Do you mean I have a struct with a generic parameter, but some fields are fixed types, and I define an impl for the struct that uses those parts that don't refer to the type parameter?
1 Like
Yes, that is what I had in mind; sorry for the awkward phrasing.
1 Like