use std::io::Write;
fn main() {/*std::io::stdin() 返回标准输入流stdin的句柄。read_line() stdin的句柄的一个方法,从标准输入流中读取一行数据返回一个Result枚举。会自动删除行尾的换行符\n。unwrap() 是一个帮助的方法,简化恢复错误的处理。返回Result中的存储实际值。*/let mut in_word = String::new();let result = std::io::stdin().read_line(&mut in_word).unwrap();println!("您输入的是:{}\n", in_word); // 您输入的是:helloprintln!("读取的字节数为:{}\n", result); // 读取的字节数为:7let result1 = std::io::stdout().write("Rust".as_bytes()).unwrap();println!("写入的字节数为:{}\n", result1); // Rust写入的字节数为:4let result2 = std::io::stdout().write("Hello".as_bytes()).unwrap();println!("写入的字节数为:{}\n", result2); // Hello写入的字节数为:5/*std::io::stdout()返回标准输出流的句柄。write()是标准输出流stdout的句柄上的一个方法,用于向标准输出流中写入字节流的内容。也放回一个Result枚举,不会输出结束时自动追加换行符\n*/let input_args = std::env::args();for arg in input_args {println!("命令行参数:{}", arg);}/*输出:命令行参数:D:\Rust\io_23\target\debug\io_23.exe命令行参数:Rust命令行参数:Programming命令行参数:Language*/
}
unwrap()
In Rust, the unwrap() method is a common way to handle error states represented by the Option and Result types.
Let’s break it down a bit:
-
Option<T>is a type in Rust that represents an optional value: everyOption<T>is eitherSome(T)(contains a value) orNone(does not contain a value). -
Result<T, E>is a type in Rust that can represent either success (Ok(T)) or failure (Err(E)).
Both Option and Result types have the method unwrap(). For an Option, calling unwrap() returns the contained value if it’s Some(T), but if it’s None, it will cause the program to panic (crash).
For a Result, calling unwrap() returns the contained value if it’s Ok(T), but if it’s Err(E), it will also cause the program to panic.
So, the unwrap() method is a somewhat risky operation to use, because while it’s a quick and easy way to obtain the inner value, it can cause your program to crash if the Option is None or the Result is an Err. In production code, it’s often preferable to handle errors more gracefully rather than using unwrap().