You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/peripherals/singletons.md
+22Lines changed: 22 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -23,6 +23,8 @@ fn main() {
23
23
24
24
But this has a few problems. It is a mutable global variable, and in Rust, these are always unsafe to interact with. These variables are also visible across your whole program, which means the borrow checker is unable to help you track references and ownership of these variables.
25
25
26
+
Up until Rust 2024, the usage of static **mutable** variable has been discouraged. Since Rust 2024, static mutable variable results in an error. Of course, there are legitimate use case of having a shared mutable state, it's just that Rust want you to really think about the scope of the mutability. We'll talk about this later when we talk about internal mutability.
27
+
26
28
## How do we do this in Rust?
27
29
28
30
Instead of just making our peripheral a global variable, we might instead decide to make a structure, in this case called `PERIPHERALS`, which contains an `Option<T>` for each of our peripherals.
@@ -128,6 +130,26 @@ fn main() {
128
130
}
129
131
```
130
132
133
+
But what is `SerialPort` anyway? Surely `SerialPort` needs to be a type that is public so that other parts of the program can import it. If we let `SerialPort` to just be an empty struct to mark ownership of data, other parts of the program might mistakenly create instance of it, which we don't want. Therefore, we must store at least one private field in it to ensure no one else could construct it, like so:
Additionally, because some references are mutable, and some are immutable, it becomes possible to see whether a function or method could potentially modify the state of the hardware. For example,
0 commit comments