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.
private struct rust
Andrei Nechaev
source share