我正在尝试解析具有与此类似的格式的特定字符串:
prefix,body1:body2
我想使用.chars
方法和其他方法,例如.take_while
和其他类似的方法:
let chars = str.chars();
let prefix: String = chars.take_while(|&c| c != ',').collect();
let body1: String = chars.take_while(|&c| c != ':').collect();
let body2: String = chars.take_while(|_| true).collect();
但是编译器抱怨道:
error: use of moved value: `chars` [E0382]
let body1: String = chars.take_while(|&c| c != ':').collect();
^~~~~
help: see the detailed explanation for E0382
note: `chars` moved here because it has type `core::str::Chars<'_>`, which is non-copyable
let prefix: String = chars.take_while(|&c| c != ',').collect();
^~~~~
我可以将它重写为普通的for
循环并累积值,但这是我想避免的。
答案 0 :(得分:3)
分隔符上的字符串split
可能最简单:
fn main() {
let s = "prefix,body1:body2";
let parts: Vec<_> = s.split(|c| c == ',' || c == ':').collect();
println!("{:?}", parts);
}
但是,如果要使用迭代器,可以通过使用Why does Iterator::take_while take ownership of the iterator?对其进行可变引用来避免使用Chars
迭代器:
let str = "prefix,body1:body2";
let mut chars = str.chars();
let prefix: String = chars.by_ref().take_while(|&c| c != ',').collect();
let body1: String = chars.by_ref().take_while(|&c| c != ':').collect();
let body2: String = chars.take_while(|_| true).collect();
有关by_ref
的详情,请参阅: