使用Clap的value_of_lossy函数时类型不匹配问题求解
问题描述
我定义了如下结构体:
pub struct Config { files: Vec<String>, // ... 其他字段 }
使用Clap库从命令行获取参数:
.arg( Arg::with_name("files") .value_name("FILE") .help("Input file(s)") .multiple(true) .default_value("-"), )
尝试为结构体赋值时:
Config { files: matches.value_of_lossy("files").unwrap(), // ... 其他字段赋值 }
出现类型不匹配错误:
error[E0308]: mismatched types --> src/lib.rs:42:16 | 42 | files: matches.value_of_lossy("files").unwrap(), | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Vec<String>`, found `Cow<'_, str>` | = note: expected struct `Vec<String>` found enum `Cow<'_, str>` For more information about this error, try `rustc --explain E0308`. error: could not compile `catr` (lib) due to previous error
请问如何从Clap获取字符串向量?我不清楚该如何转换和使用Cow类型。
解决方法
方法1:用复数版values_of_lossy直接获取Vec<String>
你误用了单值参数的方法——value_of_lossy针对单个参数返回Option<Cow<'_, str>>,而支持多值的参数应该用**values_of_lossy**(注意复数形式),它会直接返回Option<Vec<String>>,完美匹配结构体的字段类型:
Config { files: matches.values_of_lossy("files").unwrap(), // ... 其他字段 }
方法2:通过values_of手动收集转换
如果需要更灵活的处理,可以用values_of获取字符串引用的迭代器,再将每个元素转换为String并收集成向量:
Config { files: matches.values_of("files") .unwrap() .map(|s| s.to_string()) .collect(), // ... 其他字段 }
关于Cow类型的简单说明
Cow<'a, str>是"Clone-on-Write"的缩写,是一个智能枚举:它要么持有一个字符串引用&'a str,要么持有一个拥有所有权的String。如果需要把单个Cow转成String,可以调用.into_owned()方法,但针对多值参数,直接用复数版方法会更高效省心。
内容的提问来源于stack exchange,提问作者Tomasz
相关产品推荐
相关产品推荐

