Rust

Relative path in Rust

Rust is completely different with other languages such as Python, Java, Ruby..

Photo by Zbysiu Rodak on Unsplash

If you’re coming from Python, to open a file you would like to write something like below in Rust:

let file = File::open("resources/example.txt")?;

But this will not work because the type of the argument in open accept is Path.

If the file we’re working on is in the default directory of Rust (where Cargo.toml lies), we don’t need to define the path.

let file = File::open("Cargo.toml")?;

But if we’re talking about some file in different directory, we have to create path variable.

let path = Path::new("resources/graphql_queries_popular.txt");
let display = path.display();

let mut reader = my_reader::BufReader::open(&path)?;

This will work.

cuongld
tomhd

Hope it helps.

~~ PEACE ~~

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store