命令行
标准输入函数
rust
fn main() {
let mut line = String::new();
println!("Enter name:");
let num = std::io::stdin().read_line(&mut line).unwrap();
println!("Hello {}", line); // 打印可见字符
println!("type line: {:?}", line); // 打印所有字符
println!("type line.len(): {}", line.len());
println!("type num: {}", num);
}
bash
Enter name:
111
Hello 111
type line: "111\n"
type line.len(): 4
type num: 4
rust
fn main() {
let mut buf = String::new();
std::io::stdin().read_line(&mut buf).expect("Failed to read line");
// // 如果输入数组的长度小于2,则返回错误
// // 读入数组
// let mut nums = buf.split_whitespace();
// let n: usize = nums.next().unwrap().parse().unwrap();
// let m: usize = nums.next().unwrap().parse().unwrap();
// println!("n={}, m={}", n, m);
// 读入数组(以空格分割、每行元素不限制数量)
let nums: Vec<i32> = buf.split_whitespace().map(|s| s.parse::<i32>().unwrap()).collect();
for n in nums {
println!("{}", n)
}
}
标准输出流
rust
use std::io::Write;
fn main() {
std::io::stdout().write_all(b"Hello world\n");
}
命令行参数
rust
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
println!("总共有{}个命令行参数", args.len());
for arg in args {
println!("参数: {}", arg);
}
}
bash
# 第一个参数是当前程序名称
➜ firstrust git:(master) ✗ ./target/debug/firstrust
总共有1个命令行参数
参数: ./target/debug/firstrust
➜ firstrust git:(master) ✗
bash
➜ firstrust git:(master) ✗ ./target/debug/firstrust 2025 happy restart
总共有4个命令行参数
参数: ./target/debug/firstrust
参数: 2025
参数: happy
参数: restart
➜ firstrust git:(master) ✗
bash
# 如果参数中存在空格,需要用双引号或者单引号引起来
➜ firstrust git:(master) ✗ ./target/debug/firstrust 2025 "happy restart" '开心 就好 🐶哈哈' '\n'
总共有5个命令行参数
参数: ./target/debug/firstrust
参数: 2025
参数: happy restart
参数: 开心 就好 🐶哈哈
参数: \n
➜ firstrust git:(master) ✗
bash
➜ firstrust git:(master) ✗ cargo run --bin firstrust 2025 happy restart
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s
Running `target/debug/firstrust 2025 happy restart`
总共有4个命令行参数
参数: target/debug/firstrust
参数: 2025
参数: happy
参数: restart
➜ firstrust git:(master) ✗