Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a String instead of printing it to standard out?

Tags:

rust

Consider the following function:

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);
}

How do I take the last println! and turn it into a "Welcome to the castle {}".to_string(); and have the {} replaced with name (obviously I would need to add -> String to the function declaration.)

like image 889
TheWebs Avatar asked Jan 06 '23 05:01

TheWebs


1 Answers

Use the format! macro.

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)
}
like image 167
Francis Gagné Avatar answered Jan 13 '23 15:01

Francis Gagné