Public/Private struct in Rust -


i have little project , want encapsulate struct's fields , 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 leave prey 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 error:

error: struct `prey` private 

i know if put pub before struct prey {}, i'll expected result. grateful explanation, how, why not and/or best practices.

visibility works @ module level. if want module x have access item in module y, module y must make public.

modules items too. if don't make module public, it's internal crate. therefore, shouldn't worry making items in module public; crate have access it.

the crate root (usually file named lib.rs or main.rs) root module of crate. defines public interface of crate, i.e. public items in crate root accessible other crates.

in example, write mod prey;. defines prey module private, items in prey module not accessible other crates (unless reexport them pub use). means should make prey::cycle::prey public.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -