Rust エラー「error[E0369]: cannot add String to &str」が発生した場合の対処法

  • 作成日 2022.10.16
  • 更新日 2022.12.02
  • Rust
Rust エラー「error[E0369]: cannot add String to &str」が発生した場合の対処法

Rustで、エラー「error[E0369]: cannot add String to &str」が発生した場合の対処法を記述してます。Rustのバージョンは1.62.0を使用してます。

環境

  • OS windows11 home
  • rustc 1.62.0

エラー全文

以下のコードで発生

fn main() {

    let str1: &str = "aaa";
    let str2: String = "bbb".to_string();

    println!( "{}", str1 + str2 );
    
}

エラー全文

error[E0369]: cannot add `String` to `&str`
 --> sample.rs:6:26
  |
6 |     println!( "{}", str1 + str2 );
  |                     ---- ^ ---- String
  |                     |    |
  |                     |    `+` cannot be used to concatenate a `&str` with a `String`
  |                     &str
  |
help: create an owned `String` on the left and add a borrow on the right
  |
6 |     println!( "{}", str1.to_owned() + &str2 );
  |                         +++++++++++   +

error: aborting due to previous error

原因

文字列リテラルと結合する場合は、対象の変数を右にもってくる必要があるため

対処法

エラーメッセージにある通り、String に変換する「to_owned」と文字列リテラルに変換する「&」を使用して、正しい順番で結合する

fn main() {

    let str1: &str = "aaa";
    let str2: String = "bbb".to_string();

    println!( "{}", str1.to_owned() + &str2 );
    // aaabbb
    
}