Field Or Method
This section, among technical details, contains some discussion about the ways of accessing field values which expresses the author's personal opinion.
The public view of Rust is strongly opinionated about its purpose, and most see it as a systems programming language, blockchain and cryptocurrency marvel, embedded systems darling, or a WebAssembly wonder. However, somehow application development escapes the attention of the developer community (in the broad sense of the term, not the Rust community alone). I think this is a big mistake.
But before going into the details, let's think about what makes the difference between application development and systems/blockchain/embedded ones. The one directly related to the topic is the fact that the latter ones are about performance/size, while the former is about ease and speed of development. Or, in other words, 80% performance / 20% glue and interfaces vs. 20% performance / 80% glue and interfaces, respectively1.
In the context of performance-critical code, direct access to struct fields is a way to reduce memory footprint and CPU usage.
But in the context of application development, control over access to the fields is more important than performance. This is where accessors and setters come into play. They're your interface to the outside world, whether it be some third-party user of your API or even your own code. Yes, precisely, the encapsulation in its purity!
There are also cases when the usage of accessors is nearly unavoidable, such as when you need to implement lazy initialization of a field. But then again, this is something that is rather found in non-performance-critical paths, with only a few exceptions.
Not to forget, it has to be mentioned that most of the methods generated by FieldX are marked as inlinable. Moreover, accessors carry the #[inline(always)]
attribute. So, if unsure, you could always try to check the final assembly of your code to see if it is worth choosing readability over performance.
However, when there is a need to work with a field directly2, it is necessary to know what container types FieldX uses to wrap the field value. This information can be found in the Inner Workings section.