gpt4 book ai didi

rust - 如何创建一个字符串而不是将其打印到标准输出?

转载 作者:行者123 更新时间:2023-11-29 07:52:25 24 4
gpt4 key购买 nike

考虑以下函数:

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 添加到函数声明中。)

最佳答案

使用 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)
}

关于rust - 如何创建一个字符串而不是将其打印到标准输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40066150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com