Getters provide a way to enforce encapsulation by providing methods that give controlled access to struct fields. However, in structs with multiple fields, it is not unusual that copy and paste is used to quickly create the needed getters, which can result in the wrong field being accessed by a getter.
To fix the issue of incorrect field access in getters, ensure that each getter method correctly accesses the intended field.
struct MyStruct {
field1: i32,
field2: i32,
}
impl MyStruct {
// Incorrectly accessing field2 instead of field1
fn get_field1(&self) -> i32 {
self.field2
}
fn get_field2(&self) -> i32 {
self.field2
}
}
struct MyStruct {
field1: i32,
field2: i32,
}
impl MyStruct {
// Correctly accessing field1
fn get_field1(&self) -> i32 {
self.field1
}
fn get_field2(&self) -> i32 {
self.field2
}
}