在修补一个板条箱时,我自己承担了隐藏内部迭代器类型的责任,但是作者说发布该类型是一个特性,最佳实践是为公共API中公开的每个迭代器发布一个显式包装器结构。显然,Rust标准库对所有迭代器都这样做。
为什么要这样做?更具体地说,如果实现与
std::env::Args
,使用。。。
// implement iterator compatible with std::env::Args
pub struct Args { // public
// pub(crate) ...
}
impl Iterator for Args {
// ...
}
pub fn args() -> Args {
// ...
// return Args
}
// implement iterator compatible with std::env::Args
pub(crate) struct Args { // hidden (outside of crate)
// pub(crate) ...
}
impl Iterator for Args {
// ...
}
pub fn args() -> impl Iterator<Item = String> {
// ...
// return Args
}