文字列を連結するにはどうすればいいですか? 質問する

文字列を連結するにはどうすればいいですか? 質問する

次の型の組み合わせを連結するにはどうすればよいですか?

  • strそしてstr
  • Stringそしてstr
  • StringそしてString

ベストアンサー1

文字列を連結する場合、結果を格納するためのメモリを割り当てる必要があります。最も簡単に始めることができるのは、Stringと です&str

fn main() {
    let mut owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    owned_string.push_str(borrowed_string);
    println!("{owned_string}");
}

ここでは、変更可能な所有文字列があります。これは、メモリ割り当てを再利用できる可能性があるため効率的です。Stringおよびの場合Stringも同様です。&String は次のように参照できる。&str

fn main() {
    let mut owned_string: String = "hello ".to_owned();
    let another_owned_string: String = "world".to_owned();
    
    owned_string.push_str(&another_owned_string);
    println!("{owned_string}");
}

この後、another_owned_stringは変更されません(修飾語がないことに注意してください)。を消費するが、変更可能である必要がないmut別のバリエーションがあります。これはStringAdd特性の実装Stringこれは、左辺としてa を取り、&str右辺として a を取ります。

fn main() {
    let owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    let new_owned_string = owned_string + borrowed_string;
    println!("{new_owned_string}");
}

owned_stringを呼び出した後は、 にアクセスできなくなることに注意してください+

両方を変えずに新しい文字列を生成したい場合はどうすればよいでしょうか。最も簡単な方法は、format!:

fn main() {
    let borrowed_string: &str = "hello ";
    let another_borrowed_string: &str = "world";
    
    let together = format!("{borrowed_string}{another_borrowed_string}");
    println!("{}", together);
}

両方の入力変数は不変なので、変更されないことに注意してください。 の任意の組み合わせに対して同じことを行う場合は、もフォーマットできるStringという事実を利用できます。String

fn main() {
    let owned_string: String = "hello ".to_owned();
    let another_owned_string: String = "world".to_owned();
    
    let together = format!("{owned_string}{another_owned_string}");
    println!("{}", together);
}

ただし、使用する必要はありませんformat!1つの文字列を複製するそして、他の文字列を新しい文字列に追加します。

fn main() {
    let owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    let together = owned_string.clone() + borrowed_string;
    println!("{together}");
}

: 私が行ったすべての型指定は冗長です。コンパイラーはここで使用されているすべての型を推測できます。この質問は Rust 初心者の間で人気があると予想されるため、Rust 初心者にわかりやすくするために追加しました。

おすすめ記事