diff --git a/technology/dev/programming/languages/Rust.md b/technology/dev/programming/languages/Rust.md index e0a11b2..ac0c31b 100644 --- a/technology/dev/programming/languages/Rust.md +++ b/technology/dev/programming/languages/Rust.md @@ -620,6 +620,28 @@ mymacro!("Hello", "World"); This macro gets expanded to the code inside the `macro_rules!` section with the provided arguments. For more information on macros, see the [docs](https://doc.rust-lang.org/reference/macros-by-example.html). +## `unsafe` Rust +Rust is focused strongly on safety, but sometimes doing something dangerous is necessary. In this case you can use the `unsafe` keyword. `unsafe` should be used only when needed as it may cause undefinied behaviour, but when debugging you can solely focus on your `unsafe` blocks as all potential dangerous operations are neatly packaged in them. + +There are two types of using `unsafe`: +- `unsafe` blocks lets you call dangerous code. With this you can wrap unsafe code in a safe function with checks to call. +```rust +fn write_to_serial(data: &[u8]) { + assert!(data.is_valid()); + + unsafe { + // doing potentially unsafe things + write_to_serial_unchecked(data); + } +} +``` +- `unsafe` functions can only be called from `unsafe` blocks. +```rust +unsafe fn write_to_serial_unchecked(data: &[u8]) { + // unsafe operation +} +``` + ## [Crates](https://lib.rs/) - [anyhow](https://lib.rs/crates/anyhow): Flexible concrete Error type built on `std::error::Error` - [itertools](https://lib.rs/crates/itertools): Extra iterator adaptors, iterator methods, free functions, and macros