std-method

Path::try_exists: distinguish lookup failures

Test whether the path resolves, distinguishing many lookup errors from confirmed absence. The result does not reserve the name and may change before the next call. Run only inside a disposable working directory. The fixture must not already exist. Expected stdout (not executed): false true Common mistake: Using try_exists as an authorization or race-free creation check.

Formal Syntax & Structure

rust syntaxrust
path.try_exists() -> io::Result<bool>

Working Example

Example Snippetrust
fn main() {    use std::fs::{self, File, OpenOptions};    use std::io::{Read, Write};    fs::create_dir("bm-fixture").expect("use a fresh disposable directory");    let p = std::path::Path::new("bm-fixture").join("note.txt");    println!("{}", p.try_exists().unwrap());    File::create_new(&p).unwrap();    println!("{}", p.try_exists().unwrap());}
Rust Reference