Rust 文字列について

July 11, 2021

文字列 と 文字

文字列の結合

format! マクロ

format!マクロが一番わかりやすいかも。 String と str はどう組み合わせてもOK。

>> format!("{}{}", "hello", " world")
"hello world"
>> format!("{}{}", String::from("hello"), " world")
"hello world"
>> format!("{}{}", String::from("hello"), String::from(" world"))
"hello world"
>> format!("{}{}", "hello", String::from(" world"))
"hello world"

+ 演算子

https://doc.rust-lang.org/std/ops/trait.Add.html#impl-Add%3C%26%27_%20str%3E

+ 演算子は第一オペランドの所有権がムーブされる。第二オペランドは借用される。

>> String::from("hello") + " world"
"hello world"
>> String::from("hello") + &String::from(" world")
"hello world"
>> "hello".to_string() + " world"
"hello world"

Profile picture

あさくち Webエンジニアっぽい仕事をしている Twitter