我可以为我的 struct 实现Iterator
个特征,并免费实现IntoIterator
个特征,这要归功于一揽子实现.
struct Foo {}
impl Iterator for Foo {
type Item = ();
fn next(&mut self) -> Option<Self::Item> { None }
}
fn bar(foo: Foo) {
foo.into_iter(); // implemented automatically for my struct
}
但为什么我也能这么做呢?
fn bar(foo: &mut Foo) {
foo.into_iter(); // works; but shouldn't into_iter require ownership?
}
INTO_ITER方法的实现似乎需要值的所有权:
impl<I: Iterator> const IntoIterator for I {
type Item = I::Item;
type IntoIter = I;
#[inline]
fn into_iter(self) -> I {
self
}
}
当方法INTO_ITER被定义为取得所有权时,什么允许它接受可变引用?
有没有办法使下面例子中的方法move_out
表现得像方法into_iter
?
trait A {}
trait B {
fn move_out(self) -> Self;
}
impl<T: A> B for T {
fn move_out(self) -> Self {
self
}
}
struct Foo {}
impl A for Foo {}
fn bar(foo: &mut Foo) {
foo.move_out(); // compile error
}