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!
Safety
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.Examples
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