Unchecked String Slicing

I want to slice a String, and I am hundred percent sure I will do it with valid indices. As far as I understand slicing a string with a code like &s[a..b] checks if a and b are valid indexes, and panics if they are not. How can I avoid this unnecessary checking? I want this because my program will do so much slicing, and I will already be ensured that they are valid before using them in slicing. Thanks!



Callers of this function are responsible that these preconditions are satisfied:

  • The starting index must not exceed the ending index;
  • Indexes must be within bounds of the original slice;
  • Indexes must lie on UTF-8 sequence boundaries.

Failing that, the returned string slice may reference invalid memory or violate the invariants communicated by the str type.


let v = "πŸ—»βˆˆπŸŒ";
unsafe {
   assert_eq!("πŸ—»", v.get_unchecked(0..4));
   assert_eq!("∈", v.get_unchecked(4..7));
   assert_eq!("🌏", v.get_unchecked(7..11));
1 Like