次の型の組み合わせを連結するにはどうすればよいですか?
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
別のバリエーションがあります。これはString
Add
特性の実装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 初心者にわかりやすくするために追加しました。