今日の一言【2019.09.07】

今日の一言です。

Rustにて

「 String + &str 」はOK, 「 String + String 」はNG

OKパターン

fn main() {
    let hello = "Hello ".to_string();
    let world = "world!";

    let hello_world = hello + world;

    println!("{}", hello_world);    // "Hello world!" と出力される
}

NGパターン(Stringを&str にすることで解決可能)

fn main() {
    let hello = "Hello ".to_string();
    let world = "world!".to_string();

    // String + String のためNG
    // let hello_world = hello + world

    // String + &str のためOK
    let hello_world = hello + &world;    // &worldでStringが&strとなる

    println!("{}", hello_world);         // "Hello world!"と出力される
}
スポンサーリンク
レクタングル広告(大)
レクタングル広告(大)

シェアする

  • このエントリーをはてなブックマークに追加

フォローする