How do I create a custom getter or setter in a struct:
struct MyStruct {
field1: int
}
impl MyStruct {
//getter
fn field1(self) -> int {
// some calculations....
// return the value...
}
//or
//setter
fn field1(self, value) {
}
}
What's the truly Rust way to do that?
However, since in C a struct does not have functions, you'd have to have stand-alone getter and setter functions, and since getter and setter functions exist to allow you to control access, it's pretty pointless in C as there is no concept of public or private.
That's because getters are a common design pattern in Go. It is absolutely not idiomatic Golang code to use getters and setters rather than struct fields, as I am painfully aware after a day wasted wrestling with net/http and httprouter. Golang strongly prefers simple struct fields.
Yes, getters/setters can be made static based on your need.
Rust does not have anything like Python or C♯ properties at present; foo.bar
is only ever field access, never a method call. Often it makes sense to just make the field public, but if you don’t want to do that for reasons of safety or needing to have side-effects, having fn field1(&self) -> int
and fn set_field1(&mut self, value: int)
would be acceptable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With