結合
2022/1/1 12:43:00
文字列といろんなものを結合できるすごい関数マクロ
Displayが実装されていればなんでも結合できる気がする(要検証)
String と Stringの結合let hello:String = String::from("hello");
let world:String = String::from("world");
let hello_world = format!("{} {}", hello, world);
println!("{}", hello_world); //hello world
String と 文字列リテラル(&str)の結合let hello:String = String::from("hello");
let world:&str = "world";
let hello_world = format!("{} {}", hello, world);
println!("{}", hello_world); //hello world
Stringと整数型(u32)の結合let hello:String = String::from("hello");
let number:u32 = 1234;
let hello_number = format!("{} {}", hello, number);
println!("{}", hello_number); //hello 1234
fn main() {
let mut string = String::new();
println!("{}", string); //
string.push_str("hello");
println!("{}", string); //hello
let s : &str = " world";
string.push_str(s);
println!("{}", string); //hello world
}
Stringは追加できない。エラーになる。StringにStringを追加(というか結合)したいときはformatを使おう。
追加元の変数にはmutをつけておく必要がある。変更されるので。