< 返回版块
NenX 发表于 2025-07-04 17:23
Tags:求助各位大佬:我是一名 Rust 新手,学习 Rust 的时候遇到疑问1: 为什么 &s 不可以通过编译。疑问2: 为什么 &mut s 却可以呢
struct S(usize);
impl Iterator for S {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.0 == 0 {
return None;
}
let res = Some(self.0);
self.0 -= 1;
res
}
}
fn main() {
let mut s = S(5);
// for i in &s {} // 疑问1: 为什么 &s 不可以
for i in &mut s {} // 疑问2: 为什么 &mut s 可以
for i in s {} // impl<I: Iterator> IntoIterator for I
}
1
共 2 条评论, 1 页
评论区
写评论感谢大佬!
--
👇
Bai-Jinlin: 因为标准库里有
以及
所以&mut s可以&s不可以,至于为什么不对&I实现,你看看Iterator next的参数就知到了。
因为标准库里有
以及
所以&mut s可以&s不可以,至于为什么不对&I实现,你看看Iterator next的参数就知到了。