Rust编程:从输入输出到数据管理
1. 输入代码函数化
在编程中,经常会需要询问用户的姓名。为了避免重复输入相同的代码,提高代码的可读性和可维护性,我们可以将输入代码封装成一个函数。这遵循了DRY(Don’t Repeat Yourself)原则。
1.1 函数定义示例
use std::io::stdin;
fn what_is_your_name() -> String {
let mut your_name = String::new();
stdin()
.read_line(&mut your_name)
.expect("Failed to read line");
your_name
}
fn main() {
println!("Hello, what's your name?");
let name = what_is_your_name();
println!("Hello, {}", name);
}
1.2 代码解释
- 函数
what_is_your_name的签名与main函数类似,-> String表示该函数返回一个String类型的值。 -
read_line代码被移到了函数内部。 -
your_na
超级会员免费看
订阅专栏 解锁全文
11万+

被折叠的 条评论
为什么被折叠?



