Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public/Private struct in Rust

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.

like image 724
Andrei Nechaev Avatar asked Dec 01 '14 22:12

Andrei Nechaev


1 Answers

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.

like image 52
Francis Gagné Avatar answered Nov 15 '22 09:11

Francis Gagné