Writing Unsafe Functions

You can mark your own functions as unsafe if they require particular conditions to avoid undefined behaviour.

  1. /// Swaps the values pointed to by the given pointers.
  2. ///
  3. /// # Safety
  4. ///
  5. /// The pointers must be valid and properly aligned.
  6. unsafe fn swap(a: *mut u8, b: *mut u8) {
  7. let temp = *a;
  8. *a = *b;
  9. *b = temp;
  10. }
  11. fn main() {
  12. let mut a = 42;
  13. let mut b = 66;
  14. // Safe because ...
  15. unsafe {
  16. swap(&mut a, &mut b);
  17. }
  18. println!("a = {}, b = {}", a, b);
  19. }

We wouldn’t actually use pointers for this because it can be done safely with references.

Note that unsafe code is allowed within an unsafe function without an unsafe block. We can prohibit this with #[deny(unsafe_op_in_unsafe_fn)]. Try adding it and see what happens.