I have a little project and I want to encapsulate a struct's fields and use implemented methods.
├── src
├── main.rs
├── predator
└── prey
├── cycle.rs
└── mod.rs
cycle.rs
struct Prey {
name: String,
}
impl Prey {
pub fn new(n: String) -> Prey {
Prey { name: n }
}
pub fn get_name(&self) -> &str {
self.name.as_str()
}
}
I'd like to leave Prey
as private.
main.rs
use prey::cycle::Prey;
mod prey;
fn main() {
let pr = Prey::new("Hamster".to_string());
println!("Hello, world! {}", pr.get_name());
}
I get an error:
error: struct `Prey` is private
I know that if I put pub
before struct Prey {}
, I'll get the expected result. I will be grateful for an explanation, how, why not and/or best practices.
Visibility works at the module level. If you want module X to have access to an item in module Y, module Y must make it public.
Modules are items too. If you don't make a module public, then it's internal to your crate. Therefore, you shouldn't worry about making items in that module public; only your crate will have access to it.
The crate root (usually the file named lib.rs or main.rs) is the root module of your crate. It defines the public interface of the crate, i.e. public items in the crate root are accessible from other crates.
In your example, you write mod prey;
. That defines the prey
module as private, so items in the prey
module are not accessible from other crates (unless you reexport them with pub use
). That means you should make prey::cycle::Prey
public.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With