Read ZIP file by a function

I try the following to get the content of a ZIP file but I get a compilation error. Could someone give me a solution? Thank you very much:

    fn extract_records(file: &ZipFile) -> Vec<Agency> {

        let rdr = ReaderBuilder::new()
            .has_headers(true)
            .delimiter(b',')
            .trim(Trim::All)
            .flexible(true)
            .from_reader(Box::new(file))
            .into_deserialize::<Agency>()
            .map(|row| row.expect("Failed decoding row"));

        let records: Vec<_> = rdr.into_iter().map(|rec| rec).collect();
        records
    }

The error is:

error[E0277]: the trait bound `&ZipFile<'_>: std::io::Read` is not satisfied
  --> src\gtfs.rs:81:26
   |
81 |             .from_reader(Box::new(file))
   |                          ^^^^^^^^^^^^^^ the trait `std::io::Read` is not implemented for `&ZipFile<'_>`
   |
   = help: the following implementations were found:
             <ZipFile<'a> as std::io::Read>
   = note: `std::io::Read` is implemented for `&mut zip::read::ZipFile<'_>`, but not for `&zip::read::ZipFile<'_>`
   = note: required because of the requirements on the impl of `std::io::Read` for `Box<&ZipFile<'_>>`

Try passing by value or mutable reference:

-    fn extract_records(file: &ZipFile) -> Vec<Agency> 
+    fn extract_records(file: ZipFile<'_>) -> Vec<Agency> 
-    fn extract_records(file: &ZipFile) -> Vec<Agency> 
+    fn extract_records(file: &mut ZipFile<'_>) -> Vec<Agency> 
1 Like

Thank you very much, it is working exactly as expected. My whole source code. Probably some one else needs to parse CSV files from GTFS Archives too ...

let mut zip = zip::ZipArchive::new(gtfs_archive_file)?;

for i in 0..zip.len() {
    let mut file = zip.by_index(i)?;

    match file.name() {
        "agency.txt" => {
            let records = extract_records(&mut file);

            for rec in records {
                println!("{:?}", rec)
            }

        }
        &_ => println!("unhandled file: {}", file.name()),
    }

}
...
fn extract_records(file: &mut ZipFile<'_>) -> Vec<Agency> {

    let rdr = ReaderBuilder::new()
        .has_headers(true)
        .delimiter(b',')
        .trim(Trim::All)
        .flexible(true)
        .from_reader(Box::new(file))
        .into_deserialize::<Agency>()
        .map(|row| row.expect("Failed decoding row"));

    let records: Vec<_> = rdr.into_iter().map(|rec| rec).collect();
    records
}

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.