我找到了以下定义std::borrow::BorrowMut:
pub trait BorrowMut<Borrowed>: Borrow<Borrowed>
where
Borrowed: ?Sized,
{
fn borrow_mut(&mut self) -> &mut Borrowed;
}
Run Code Online (Sandbox Code Playgroud)
Sized在这个类型参数bound(Borrowed: ?Sized)中,问号前面的问号是什么?
我咨询过:
但没有找到解释.请在答案中提供参考.
要在Rust中实现迭代器,我们只需要实现该next方法,如文档中所述.然而,该Iterator特征有更多的方法.
据我所知,我们需要实现特征的所有方法.例如,这不编译(playground链接):
struct SomeStruct {}
trait SomeTrait {
fn foo(&self);
fn bar(&self);
}
impl SomeTrait for SomeStruct {
fn foo(&self) {
unimplemented!()
}
}
fn main() {}
Run Code Online (Sandbox Code Playgroud)
错误很明显:
error[E0046]: not all trait items implemented, missing: `bar`
--> src/main.rs:8:1
|
5 | fn bar(&self);
| -------------- `bar` from trait
...
8 | impl SomeTrait for SomeStruct {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `bar` in implementation
Run Code Online (Sandbox Code Playgroud) 从std::iter::Iterator文档中,我可以看到只next需要方法:
所需方法
Run Code Online (Sandbox Code Playgroud)fn next(&mut self) -> Option<Self::Item>
但是从源代码中删除注释后:
pub trait Iterator {
/// The type of the elements being iterated over.
#[stable(feature = "rust1", since = "1.0.0")]
type Item;
......
#[stable(feature = "rust1", since = "1.0.0")]
fn next(&mut self) -> Option<Self::Item>;
......
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
......
}
Run Code Online (Sandbox Code Playgroud)
我可以看到,除了#[inline]属性,必需方法和提供的方法之间没有区别.Rust如何知道需要或提供哪种方法?