我正在尝试解析具有类似于此格式的特定字符串:
prefix,body1:body2
Run Code Online (Sandbox Code Playgroud)
我想使用像这样的.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();
Run Code Online (Sandbox Code Playgroud)
(游乐场)
但是编译器抱怨:
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();
^~~~~
Run Code Online (Sandbox Code Playgroud)
我可以将它重写为一个简单的for循环并累积该值,但这是我想避免的。
仅split使用分隔符上的字符串可能是最简单的:
fn main() {
let s = "prefix,body1:body2";
let parts: Vec<_> = s.split(|c| c == ',' || c == ':').collect();
println!("{:?}", parts);
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您想使用迭代器,则可以Chars通过以下方式对其进行可变引用来避免使用迭代器Iterator::by_ref:
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();
Run Code Online (Sandbox Code Playgroud)
有关更多信息by_ref,请参阅:
| 归档时间: |
|
| 查看次数: |
669 次 |
| 最近记录: |