Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom getters and setters in a struct

Tags:

rust

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?

like image 824
Incerteza Avatar asked Oct 30 '14 01:10

Incerteza


People also ask

Can structs have getters and setters?

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.

Should I use getters and setters in Golang?

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.

Can getter be static?

Yes, getters/setters can be made static based on your need.


1 Answers

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.

like image 138
Chris Morgan Avatar answered Sep 29 '22 11:09

Chris Morgan