How do I do == with the current directory I am in?

Hi, I am getting this error:

 |     if dir.display() == r"C:\Users\Joe\Desktop"
   |        ------------- ^^ ----------------------- &str
   |        |
   |        std::path::Display<'_>

error: aborting due to previous error; 2 warnings emitted

For more information about this error, try `rustc --explain E0369`.
error: could not compile `test`

To learn more, run the command again with --verbose.

After I ran this code:

fn main()
{
    use std::env;

    let dir = env::current_dir().unwrap();
    println!("{}", dir.display());

    if dir.display() == r"C:\Users\Joe\Desktop"
    {
        
    }
}

I just want to be able to use an if statement based on what directory I am in so how would I exactly fix this and like why would == work?

if dir.display().to_string()

Just needed to add this!

But how does to_string() convert the data type?

Don't rely on .display() for deterministic output results. It's a std::path::Display, whose output is only intended for printing purposes. If you want to check for equality, you need any of the types listed to be comparable to Path, or PathBuf. The easiest way is as follows:

if dir == Path::new(r"C:\Users\Joe\Desktop") {
    //
}

This impl.

3 Likes

Thanks but what is the difference between Path and PathBuf?

Same difference as with str and String respectively: You own and can grow a PathBuf, but cannot do the same for a Path.

1 Like

Is there more overhead using PathBuf when I am creating an immutable variable?

More overhead over what? Path cannot exist alone, since it doesn't own its data.

YOu know how if you have &str vs String::from() it has more overhead as I have heard, so I was wondering if this was the same thing when we store the variable using Path vs PathBuf?

Storing it in a PathBuf first would incur a detriment to runtime performance, yes, that's why I suggested the use of Path::new. Taking a look at the source for that, it's nothing more than a few pointer casts:

pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
    unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
}
2 Likes

The thing I'm trying to say is that this is impossible. Path, like str, can't be used to store anything, unless it is a compile-time constant embedded in the binary.

so like if I typed let x: &str = "testing" this doesn't store anything?

That's the equivalent of

let x: Path = Path::new("testing");

In both cases the actual value is stored in the binary itself. The variable x just references it.

For example:

(~/b)$ cargo r
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/b`
Hello, world!
(~/b)$ strings target/debug/b | rg Hello
Hello, world!
1 Like

Quoting my previous post, which you seemingly didn't want to read:

Or maybe I lack understanding?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.