我很困惑可变引用如何在 for 循环中工作,而不可变引用则不然。它是一个迭代器吗?
我发现在循环之后,引用chars
引用了值""
。
无引用
fn main() {
let str_value: String = "abc".to_string();
let chars = str_value.chars();
for char_value in chars {
println!("char: {}", char_value);
}
}
char: a
char: b
char: c
不可变引用
fn main() {
let str_value: String = "abc".to_string();
let chars = str_value.chars();
for char_value in &chars {
println!("char: {}", char_value);
}
}
error[E0277]: `&std::str::Chars<'_>` is not an iterator
--> src/main.rs:5:23
|
5 | for char_value in &chars {
| -^^^^^
| |
| `&std::str::Chars<'_>` is not an iterator
| help: consider removing the leading `&`-reference
|
= help: the trait `std::iter::Iterator` is not implemented for `&std::str::Chars<'_>`
= note: `std::iter::Iterator` is implemented for `&mut std::str::Chars<'_>`, but not for `&std::str::Chars<'_>`
= note: required by `std::iter::IntoIterator::into_iter`
可变引用
fn main() {
let str_value: String = "abc".to_string();
let mut chars = str_value.chars();
for char_value in &mut chars {
println!("char: {}", char_value);
}
// why chars equal ""?
assert_eq!(chars.as_str(), "");
}
char: a
char: b
char: c
最佳答案
chars
的类型为 Chars
其中implements ("is a") iterator其元素类型为 char
.
在 Rust 中,您可以使用 for
-loops on things that implement ("are a") iterator .
因此,您的第一个示例包含在以下内容中:Iterates over char
s。
第二个示例不起作用,因为 &chars
的类型为 &Chars
(借用的、不可变的引用),它不实现 迭代器
。
但是,在第三个示例中,您有 &mut Chars
和 this is an iterator :
impl<I: Iterator + ?Sized> Iterator for &mut I { type Item = I::Item; fn next(&mut self) -> Option<I::Item> { (**self).next() } // some details omitted }
上面说:对于任何类型 I
,它是一个 Iterator
并且可能不满足 ?Sized
(所有这些都适用于该类型Chars
),类型 &mut I
是一个 Iterator
,其迭代值与原始迭代类型相同 (type Item = I::Item
),并将 next
(和一些其他方法)委托(delegate)给原始迭代器。
因此,第三个示例看到 &mut Chars
,知道 Chars
是一个 Iterator
,并推断出 &mut Chars
也是一个可以在 for
循环中使用的迭代器
。
as_str
-- 根据其文档(请参阅此处的示例)为您提供剩余的(即尚未迭代的)子字符串,因此在迭代之后,它应该只是说 ""
(即空),因为有没有什么需要迭代的了。
关于rust - 在字符串字符 for 循环中使用可变或不可变引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60128126/