46.2.1Getting a slice from a UTF-8 string¶
Compiler error:
let s = "Салам";
println!("s: {}", &s[0..1]);
thread '<unnamed>' (52188) panicked at src/lib.rs:96:21:
end byte index 1 is not a char boundary; it is inside 'С' (bytes 0..2 of string)
stack backtrace:
0: __rustc::rust_begin_unwind
at /rustc/58cf8f9c35b355199727627d07ae34a4e2846d67/library/std/src/panicking.rs:679:5
1: core::panicking::panic_fmt
at /rustc/58cf8f9c35b355199727627d07ae34a4e2846d67/library/core/src/panicking.rs:80:14
2: core::str::slice_error_fail_rt
3: core::str::slice_error_fail
at /rustc/58cf8f9c35b355199727627d07ae34a4e2846d67/library/core/src/str/mod.rs:70:5
4: __rust_try
5: run_user_code_1
6: <evcxr::runtime::Runtime>::run_loop
7: evcxr::runtime::runtime_hook
8: evcxr_jupyter::main
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
Runtime error (panic):
let s = String::from("Салам");
println!("s: {}", &s[0..1]);Couldn't automatically determine type of variable `s`.
Please give it an explicit type.We use the get() method:
{
let s = String::from("Салам");
if let Some(t) = s.get(0..1) {
println!("s[0..1]: {t}");
}
if let Some(t) = s.get(0..2) {
println!("s[0..2]: {t}");
}
}s[0..2]: С
()