Struct vector as a struct variable

Hi everyone,
I am trying something to return a HashMap from mod to main. The following code gives an error.

mod process{
    use std::collections::HashMap;
    
    #[derive(Debug)]
    struct Company {
        name: String,
        employee: Vec<Employee>,
    }
    #[derive(Debug)]
    struct Employee{
        name: String,
        age: i32
    }
    
    pub fn my_func()->HashMap<String, Company>{
        let employee1 = Employee{name:"John".to_string(), age: 20};
        let employee2 = Employee{name:"Josh".to_string(), age: 25};
        let my_vec = vec![employee1, employee2];
        let com = Company{name:"My Company".to_string(), employee: my_vec};
        
        let mut map = HashMap::new();
        //map.insert("Deneme".to_string(), com);
        map.insert("map_key".to_string(), com);
        return map;
    }
}

fn main() {
    let result = process::my_func();
	let my_data = result.get(&"map_key".to_owned()).unwrap();
	
	for i in 0..my_data.employee.len() {
        println!("Data : {}", my_data.employee[i].name);
    }

}

The error is as follows

error[E0616]: field `employee` of struct `Company` is private
  --> src/main.rs:38:22
   |
38 |     for i in 0..my_data.employee.len() {
   |                         ^^^^^^^^ private field

error[E0616]: field `employee` of struct `Company` is private
  --> src/main.rs:39:39
   |
39 |         println!("Data : {}", my_data.employee[i].name);
   |                                       ^^^^^^^^ private field

error[E0616]: field `name` of struct `Employee` is private
  --> src/main.rs:39:51
   |
39 |         println!("Data : {}", my_data.employee[i].name);
   |                                                   ^^^^ private field

For more information about this error, try `rustc --explain E0616`.

However, when I make everything public, it works. So, is there anyway to use it without having all of them public? I mean I just want to make my_func() public and call it from main which returns me corresponding HasMap

Add accessor functions.

I rewrote this code (without the HashMap, since that's not an issue here) in idiomatic Rust with methods that allow you to get read-only access to the structure's fields.

The entirety of The Book is great, but the chapters on module scope and object-oriented patterns might be especially helpful.

Removed clippy lints from @Rustaceous's answer: playground.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.