How to create a line instead of printing it to the standard?

Consider the following function:

use std::io;

pub fn hello() {
    println!("Hello, How are you doing? What 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);
}

How to take the latter println!and turn it into "Welcome to the castle {}".to_string();and replace {}with name(obviously, I need to add -> Stringfunctions to the declaration.)

+4
source share
1 answer

Use a macro format!.

pub fn hello() -> String {
    println!("Hello, How are you doing? What 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)
}
+9
source

Source: https://habr.com/ru/post/1657894/


All Articles