find the extension of a csv file in rust

To find the extension of a CSV file in Rust, we can use the std::path::Path API. Assuming file_path is the path of the file, we can get the extension by calling the extension method and then convert it to a string using the to_str method. Here's how we can do it:

main.rs
use std::path::Path;

fn main() {
    let file_path = "example.csv";
    let extension = Path::new(file_path)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("");
    
    println!("{}", extension);
}
227 chars
12 lines

The extension method returns an Option<OsStr> which we can convert to a string by calling to_str(). The and_then method takes a closure which returns an Option and if the Option is Some, it executes the closure and returns the result. If it's None, it returns None.

In our case, if the file has an extension, we return the string representation of the extension. Otherwise, we return an empty string.

gistlibby LogSnag