如何隐藏子模块中的方法但仍可从父模块中使用它?
How can I hide a method in a child module but still use it from a parent module?
我在 crate root 中定义了一个父结构,returns 一个在模块中定义的结构。我希望我的父结构是唯一能够构建子结构的东西,但我很快 运行 通过我天真的尝试进入可以理解的隐私和可见性问题:
#![feature(unsafe_destructor)]
mod child {
pub struct Child(u8);
impl Child {
fn new(v: u8) -> Child { Child(v) }
}
}
struct Parent;
impl Parent {
fn child(&self) -> child::Child {
child::Child::new(42)
}
}
fn main() {}
首先,你的 Child
结构必须是 public,如果它是由 Parent
的方法返回的话。因此你需要一个
pub use child::Child;
此外,这意味着 Child
的实现也将是 public,包括 new()
方法。为防止这种情况,您可以将其移至外部辅助方法,这样您将 不会 重新导出。
此外,Child
结构应该至少有一个私有字段,如果您不希望它可以使用 Child(42)
语法构建。
最后,你有这样的东西:
pub use child::Child;
mod child {
pub struct Child {
v: u8
}
pub fn build_child(v: u8) -> Child {
Child { v: v }
}
impl Child {
fn val(&self) -> u8 {
self.v
}
}
}
struct Parent;
impl Parent {
fn child(&self) -> Child {
child::build_child(42)
}
}
这里,child::build_child(..)
是唯一能够创建Child
实例的方法,它在包含Parent
.[=21=定义的模块之外是不可见的]
我在 crate root 中定义了一个父结构,returns 一个在模块中定义的结构。我希望我的父结构是唯一能够构建子结构的东西,但我很快 运行 通过我天真的尝试进入可以理解的隐私和可见性问题:
#![feature(unsafe_destructor)]
mod child {
pub struct Child(u8);
impl Child {
fn new(v: u8) -> Child { Child(v) }
}
}
struct Parent;
impl Parent {
fn child(&self) -> child::Child {
child::Child::new(42)
}
}
fn main() {}
首先,你的 Child
结构必须是 public,如果它是由 Parent
的方法返回的话。因此你需要一个
pub use child::Child;
此外,这意味着 Child
的实现也将是 public,包括 new()
方法。为防止这种情况,您可以将其移至外部辅助方法,这样您将 不会 重新导出。
此外,Child
结构应该至少有一个私有字段,如果您不希望它可以使用 Child(42)
语法构建。
最后,你有这样的东西:
pub use child::Child;
mod child {
pub struct Child {
v: u8
}
pub fn build_child(v: u8) -> Child {
Child { v: v }
}
impl Child {
fn val(&self) -> u8 {
self.v
}
}
}
struct Parent;
impl Parent {
fn child(&self) -> Child {
child::build_child(42)
}
}
这里,child::build_child(..)
是唯一能够创建Child
实例的方法,它在包含Parent
.[=21=定义的模块之外是不可见的]