中級 › byte index is not a char boundary パニックの原因と直し方 › パターン2
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 `ありがとう`
空欄を埋めて実行を通す
英語の感覚で1文字ずつバイト数を数えると、マルチバイト文字の途中を指してしまいます。
次の問題