Skip to content

str::slice_unchecked

str methods · Strings

Level: reference · for working programmers

Deprecated — use str::get_unchecked instead. The page is here because the name is still in older code, and it still compiles; a new call site should not use it.

One line: The 1.0-era spelling of get_unchecked, taking two usize arguments instead of a range.

pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str

Stable since 1.0.0. unsafe — the caller carries the invariant described below.

s.slice_unchecked(a, b) is s.get_unchecked(a..b). Deprecated in Rust 1.29 when the range-taking form arrived, because two loose integers invite the arguments being swapped in a way a range does not.

The safety contract is unchanged: both offsets in range, both on character boundaries.

Example

str_slice_unchecked.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

#![allow(deprecated)]

fn main() {
    let s = "héllo";

    let old = unsafe { s.slice_unchecked(0, 3) };
    let new = unsafe { s.get_unchecked(0..3) };
    println!("{old:?} {new:?}");
    println!("identical: {}", old == new);
}

Verified output of str_slice_unchecked.rs — regenerated by tools/run_examples.py, never hand-typed.

"hé" "hé"
identical: true

See also

str::slice_unchecked in the standard library ↗

Po polsku

Ta nazwa jest wycofana (deprecated) od Rusta 1.29 i powód jest czysto ergonomiczny: dwie luźne liczby usize można podać w odwrotnej kolejności, a zakresu a..b już tak łatwo nie odwrócisz — dlatego dziś pisze się get_unchecked(a..b). Sam kontrakt się nie zmienił i to on jest tu ważny dla polskiego czytelnika: przesunięcia liczy się w bajtach, nie w znakach, a każda polska litera diakrytyczna (ą, ć, ę, ł, ń, ó, ś, ź, ż) zajmuje w UTF-8 dwa bajty — dokładnie jak é w przykładzie, gdzie 0..3 wycina "hé", a nie trzy litery. Przy zwykłym indeksowaniu takie pudło kończy się paniką z komunikatem o granicy znaku (char boundary); przy unsafe nie ma żadnej kontroli, więc kończy się zachowaniem niezdefiniowanym (undefined behaviour), które może objawić się dopiero kilka funkcji dalej.

Szukaj po polsku: przesunięcia w bajtach a znaki · granica znaku UTF-8 · metoda wycofana · rust slice_unchecked deprecated · rust str byte index char boundary