Mathe Eliel
Mathe Eliel

Reputation: 738

Print value in a vec from another module : field of struct is private

I am not able to print values from a Vec from a module, could you please help?

Here is the content of the function in the module:

pub struct Author {
    _id: i32,
    name: String,
    country: String
}

pub fn get_saved_records() -> Result<Vec<Author>,Error>{
    let mut client = Client::connect("postgresql://***:***@localhost/****",NoTls)?;
    let records = client.query("SELECT * FROM author",&[])?;
    let mut the_records : Vec<Author> = vec![];
    for record in records{
        let author = Author {
            _id: record.get(0),
            name: record.get(1),
            country: record.get(2),
        };
        the_records.push(author);
    }


    Ok(the_records)
}

Here is the main file where I call get_saved_records() function:

match db::get_saved_records(&mut conn){
                    Ok(records) => {
                        for record in records{
                            println!("{}",record.name);
                        }

                    },
                    Err(_) => println!("No record found")
                }

I am getting the error message: field name of struct db::Author is private.

Thank you.

Upvotes: 2

Views: 132

Answers (1)

prog-fh
prog-fh

Reputation: 16850

The members of your struct need to be declared pub in order to be directly accessible.

Here, only the name member is accessible.

pub struct Author {
    _id: i32,
    pub name: String,
    country: String
}

Note that it makes sense for a struct to be public while having its members private. This ensures encapsulation: the members of the struct are only accessible from the methods of its implementation (and the surrounding code in the module). Of course, those methods can also be made public or private.

Upvotes: 4

Related Questions