Skip to content

Instantly share code, notes, and snippets.

@kquick
Created November 9, 2017 17:54
Show Gist options
  • Save kquick/f748c3f0a83abd61e61ee9c448abd2f8 to your computer and use it in GitHub Desktop.
Save kquick/f748c3f0a83abd61e61ee9c448abd2f8 to your computer and use it in GitHub Desktop.
Rust iterator mystery
use std::fs;
use std::path::PathBuf;
fn show_sizes_vec(file_list: &Vec<PathBuf>) -> u64 {
let sizes = file_list
.iter()
.map(|e| fs::metadata(e).map(|m| m.len()).unwrap())
.collect::<Vec<u64>>();
let totsize : u64 = sizes.iter().sum();
println!("Total size = {}", totsize);
for each in file_list.iter().zip(sizes.iter())
{
println!(" {} {}", each.1, each.0.to_str().unwrap());
}
totsize
}
fn show_sizes_iter(file_list: &Vec<PathBuf>) -> u64 {
let mut sizes = file_list
.iter()
.map(|e| fs::metadata(e).map(|m| m.len()).unwrap());
let totsize : u64 = sizes.by_ref().sum();
println!("Total size = {}", totsize);
for each in file_list.iter().zip(sizes.by_ref())
{
println!(" {} {}", each.1, each.0.to_str().unwrap());
}
totsize
}
fn main() {
println!("OK, let's get to work!");
let file_list = fs::read_dir(".").unwrap().map(|e| e.unwrap().path()).collect::<Vec<PathBuf>>();
println!("Files: {:?}", file_list);
let count = file_list.len();
println!("--------------------");
println!("Sizes (by iteration):");
let totsize = show_sizes_iter(&file_list);
println!("{} files, {} bytes", count, totsize);
println!("--------------------");
println!("Sizes (by vec):");
let totsize = show_sizes_vec(&file_list);
println!("{} files, {} bytes", count, totsize);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment