Member-only story

Rust

Relative path in Rust

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

Donald Le

--

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 ~~

--

--

No responses yet