Skip to content

Commit 10610e4

Browse files
committed
modify singletons.md
1 parent 0b8219a commit 10610e4

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/peripherals/singletons.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ fn main() {
2323

2424
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.
2525

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+
2628
## How do we do this in Rust?
2729

2830
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() {
128130
}
129131
```
130132

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:
134+
135+
```rust, ignore
136+
137+
struct SerialPort(());
138+
139+
struct Peripherals {
140+
serial: Option<SerialPort>,
141+
}
142+
impl Peripherals {
143+
fn take_serial(&mut self) -> SerialPort {
144+
let p = replace(&mut self.serial, None);
145+
p.unwrap()
146+
}
147+
}
148+
static mut PERIPHERALS: Peripherals = Peripherals {
149+
serial: Some(SerialPort(())),
150+
};
151+
```
152+
131153
## Treat your hardware like data
132154

133155
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

Comments
 (0)