Intermediary between public and private members
Say I were to have a struct Foo { pub public: Bar, restricted: Qux } where ‘restricted’ is some member variable which I want to be able to get, but not set, from outside of the struct methods. Normally, I would write a getter method impl Foo { pub fn restricted(&self) -> &Qux { self.restricted }} which isn’t very much typing, and probably I could generate these automatically with an IDE or a…
In Rust, a struct Foo can be defined with a member variable 'restricted' that can be accessed but not modified from outside the struct methods. This is achieved by implementing a getter method `pub fn restricted(&self) -> &Qux { self.restricted }`. While this approach is not overly cumbersome and can even be automated using an IDE or plugin, it would be more convenient if Rust had a dedicated syntax to express this behavior directly in the struct declaration.
The proposed syntax would allow for three distinct access levels: private, read-only (akin to "read"), and publicly accessible. For instance, a struct could be defined as `struct Foo { x, read y, pub z }`. In this scenario, `x` would be inaccessible outside the struct and could only be accessed or modified by member functions. The `y` field would be readable by anyone but immutable, while `z` would be fully accessible for both reading and writing.
Implementing such a feature would require careful consideration of language design complexities. Specifically, the distinction between accessing and mutating a field, like `y`, would need to be addressed effectively. Despite these challenges, the added verbosity might not significantly impact ergonomics, making it a worthwhile addition to the language.
The default behavior of `read` being a more sensible default than full privacy could streamline code and improve readability. This approach could elevate Rust's usability, particularly for developers coming from languages with similar access control mechanisms. The community's input on this proposed feature would be invaluable, as it could potentially enhance Rust's appeal and practicality for a broader range of use cases.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.