Read from a file and return a struct


We have some data file that looks like this:


examples/struct/read-from-file/animals.txt
cat,4
dog,4
spider,8
human,2
insects,6

We would like to create a function that will read the file and return a vector of structs representing the data.


examples/struct/read-from-file/src/main.rs
use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader};

#[derive(Debug)]
#[allow(dead_code)]
struct Animal {
    name: String,
    legs: u8,
}

fn main() {
    let animals = read_file();
    println!("{:?}", animals);
}


fn read_file() -> Result<Vec<Animal>, Box<dyn Error>> {
    let filename = "animals.txt";
    let fh = File::open(filename)?;
    let reader = BufReader::new(fh);
    let mut animals = vec![];
    for line in reader.lines() {
        let line = line?;
        let pieces = line.split(',').collect::<Vec<_>>();
        animals.push(Animal {
            name: pieces[0].to_string(),
            legs: pieces[1].parse()?,
        })
    }

    Ok(animals)
}
In this case we cannot defined the name field to be &str as that will not work well with the function reading the data from a file. The read_file will read in the content of the file into owned string. From that we could create structs that have references in them, but when we return the structs from the functions the owner of that data will go out of scope and we'll get a compilation error: borrowed value does not live long enough