Implement struct methods to do something on specific field
⚓ Rust 📅 2025-09-25 👤 surdeus 👁️ 18Hello, I have the following situation, that is best explained with the code below.
I have a struct with multiple similar fields, that I need to modify by calling a kind-of-setter method that calls other methods implemented on the struct.
This single setter method should modify the given field, however as I also require other methods implemented on the struct, I need to parse the struct instance as well as the reference to the field.
This doesn't work in Rust because now I have multiple mutable references to basically the same variable.
struct SomeStruct {
a: u8,
y: u8,
foo: u64
};
impl SomeStruct {
fn i_need_to_call_this(&mut self) {
self.foo = 0;
}
fn write_to_field(&mut self, reference_to_field: &mut u8) {
self.i_need_to_call_this();
*reference_to_field = 42;
}
}
fn main() {
let mut this_struct: SomeStruct = SomeStruct { a:0, y: 1, foo: 2 };
// These two will fail
this_struct.write_to_field(&mut this_struct.a);
this_struct.write_to_field(&mut this_struct.y);
}
I found this solution (How to pass a field name of a struct to a method of that struct? - #2 by jofas) that uses an enum representing the fields to choose between them.
However this requires that I remember to also update the enum when making changes (removing / adding fields) to the struct.
Are there other solutions that I'm not considering?
*reference_to_field = 42; would work if I don't pass the reference to the struct instance along, however I need that to call the i_need_to_call_this method ... ![]()
3 posts - 2 participants
🏷️ Rust_feed