Rust 命令行程序参数解析与文件处理实战
1. 字符串转数字的单元测试编写
在命令行程序中,所有参数都是字符串形式,因此需要将其解析为有效的整数值。 str::parse 函数可将字符串切片解析为其他类型,如 usize 。为了完成此功能,我们编写了 parse_positive_int 函数,尝试将字符串值解析为正的 usize 值。
fn parse_positive_int(val: &str) -> MyResult<usize> {
unimplemented!();
}
为了测试这个函数,我们编写了单元测试:
#[test]
fn test_parse_positive_int() {
// 3 是有效的整数
let res = parse_positive_int("3");
assert!(res.is_ok());
assert_eq!(res.unwrap(), 3);
// 任何字符串都是错误
let res = parse_positive_int("foo");
assert!(res.is_err());
assert_eq!(res.unwrap_err().to_string(), "foo".to_string());
// 零是错误
let res = pa
超级会员免费看
订阅专栏 解锁全文
5万+

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



