设计模式
使用format!串联字符串
Description
可以在可变的String上使用push和push_str方法来建立字符串,或者使用其+操作符。 然而,使用format!往往更方便,特别是在有字面和非字面字符串混合的地方。
Example
fn say_hello1(name: &str) -> String {let mut result: String = "hello ".to_owned();result.push_str(string: name);result.push(ch: '!');result}fn say_hello2(name: &str) -> String {format!("hello {}!", name)}fn main() {let s: &str = "world";println!(say_hello1(s)); // hello world!println!(say_hello2(s)); // hello world!}
显然使用format!通常是组合字符串的最简洁和可读的方式。