如何创建一个String而不是将其打印到标准输出?

时间:2016-10-16 02:15:47

标签: rust

考虑以下功能:

use std::io;

pub fn hello() {
    println!("Hello, How are you doing? What's your characters name?");

    let mut name = String::new();

    io::stdin().read_line(&mut name).expect("Failed to read name. What was that name again?");

    println!("Welcome to the castle {}", name);
}

如何使用上一个println!并将其转换为"Welcome to the castle {}".to_string();并将{}替换为name(显然我需要添加-> String到函数声明。)

1 个答案:

答案 0 :(得分:9)

使用format!宏。

pub fn hello() -> String {
    println!("Hello, How are you doing? What's your characters name?");

    let mut name = String::new();

    io::stdin().read_line(&mut name).expect("Failed to read name. What was that name again?");

    format!("Welcome to the castle {}", name)
}