t_wの輪郭

format

2022/2/19 15:00:00

文字列といろんなものを結合できるすごい関数マクロ
Displayが実装されていればなんでも結合できる気がする(要検証)


StringStringの結合

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

push_str

2022/2/19 14:54:00

String文字列リテラル(&str)を追加する関数

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は追加できない。エラーになる。StringStringを追加(というか結合)したいときはformatを使おう。

追加元の変数にはmutをつけておく必要がある。変更されるので。