中級 › byte index is not a char boundary パニックの原因と直し方 › パターン4
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 2 is not a char boundary; it is inside 'ね' (bytes 0..3) of `ねこ`
空欄を埋めて実行を通す
バイト境界でない位置を指定した瞬間に、Rustはその場でパニックして誤ったスライスを防ぎます。
次の問題