Calling Unsafe Functions

A function or method can be marked unsafe if it has extra preconditions you must uphold to avoid undefined behaviour:

  1. fn main() {
  2. let emojis = "🗻∈🌏";
  3. // Safe because the indices are in the correct order, within the bounds of
  4. // the string slice, and lie on UTF-8 sequence boundaries.
  5. unsafe {
  6. println!("emoji: {}", emojis.get_unchecked(0..4));
  7. println!("emoji: {}", emojis.get_unchecked(4..7));
  8. println!("emoji: {}", emojis.get_unchecked(7..11));
  9. }
  10. println!("char count: {}", count_chars(unsafe { emojis.get_unchecked(0..7) }));
  11. // Not upholding the UTF-8 encoding requirement breaks memory safety!
  12. // println!("emoji: {}", unsafe { emojis.get_unchecked(0..3) });
  13. // println!("char count: {}", count_chars(unsafe { emojis.get_unchecked(0..3) }));
  14. }
  15. fn count_chars(s: &str) -> usize {
  16. s.chars().map(|_| 1).sum()
  17. }