Rust エラー「panicked at ‘byte index 2 is not a char boundary; it is inside ‘x’ (bytes 0..3) of xxx」が発生した場合の対処法

Rust エラー「panicked at ‘byte index 2 is not a char boundary; it is inside ‘x’ (bytes 0..3) of xxx」が発生した場合の対処法

Rustで、エラー「panicked at ‘byte index 2 is not a char boundary; it is inside ‘x’ (bytes 0..3) of xxx」が発生した場合の対処法を記述してます。Rustのバージョンは1.62.1を使用してます。

環境

  • OS windows11 home
  • rustc 1.62.1

エラー全文

以下のコードで発生

fn main() {

    let mut str: String = "あいうえお".to_string();

    println!( "{}", str.remove(2) );    
    println!( "{}", str );    

}

エラー全文

thread 'main' panicked at 'byte index 2 is not a char boundary; it is inside 'あ' (bytes 0..3) of `あいうえお`', library\core\src\str\mod.rs:127:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\rust_sample.exe` (exit code: 101)

原因

日本語で「remove」を使用する際に、引数は「3」の倍数単位で指定する必要があるため

対処法

「3」の倍数単位で指定する

fn main() {

    let mut str: String = "あいうえお".to_string();

    println!( "{}", str.remove(0) ); // あ  
    println!( "{}", str ); // いうえお

    str = "あいうえお".to_string();

    println!( "{}", str.remove(3) ); // い
    println!( "{}", str ); // あうえお

}

実行結果