Saturday, June 28, 2014

Rust note 6: Checking to see if a file exists in Rust

use std::path;
fn alreadyExists(items: Vec<Path>, quer: &str) -> bool {
    items.iter().any(|nms: &Path| -> (bool) {nms == &Path::new(quer)})
}


This searches over the items iterator, checking each path against a filename, and returns "true" if the file exists in the directory, or "false" otherwise. It does this by way of a higher-order function (.any) that takes individual &Path's and checking them against a temporary reference to a Path that has the same file name as what is being searched.

This approach is a tad bit intensive, since you will be putting a lot of temporary objects on the heap. However, the overall net effect on memory should be 0 since they all fall out of scope during each iteration of the iterator.

No comments:

Post a Comment