中級 › byte index is not a char boundary パニックの原因と直し方 › パターン5
byte index is not a char boundary パニックの原因と直し方
Rustの文字列はUTF-8のバイト列として保持されており、日本語のようなマルチバイト文字の途中の位置でスライスしようとするとパニックします。
1 fn main() { 2 let s = String::from("さくら"); 3 let slice = &s[0.._]; ^ 4 println!("{}", slice); 5 }
thread 'main' panicked at main.rs:3:19:
byte index 1 is not a char boundary; it is inside 'さ' (bytes 0..3) of `さくら`
空欄を埋めて実行を通す
文字列のバイト長とその文字列が何文字かは、マルチバイト文字を含む限り一致しません。
次の問題