Public / Private Structure in Rust

I have a small project, and I want to encapsulate the structure fields and use the 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 would like to leave Prey closed.

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 message:

 error: struct `Prey` is private 

I know that if I put pub before struct Prey {} , I will get the expected result. I will be grateful for an explanation of how, why not, and / or best practices.

+7
private struct rust
source share
1 answer

Visibility works at the module level. If you want module X to have access to item in module Y, module Y must make it public.

Modules are also elements. If you do not make the module public, then it is internal to your mailbox. Therefore, you should not worry about publishing items in this module; only your box will have access to it.

The root box (usually a file named lib.rs or main.rs) is the root module of your box. It defines the open box interface, i.e. Public items at the root of the box are accessible from other boxes.

In your example, you write mod prey; . This defines the prey module as private, so the elements in the prey module are not available from other mailboxes (unless you re-export them using pub use ). This means that you must make prey::cycle::Prey public.

+8
source share

All Articles