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

The*_*ebs 4 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);
}
Run Code Online (Sandbox Code Playgroud)

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

Fra*_*gné 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)
}
Run Code Online (Sandbox Code Playgroud)