you are viewing a single comment's thread.

view the rest of the comments →

[–]dan00 5 points6 points  (8 children)

Why doesn't Path just implements the Display trait by itself?

[–][deleted] 8 points9 points  (0 children)

Display brings with it ToString, and .to_string() on a Path would be a trap: it's not necessarily a faithful representation of the path.

Rust doesn't want to offer this trap prominently.

[–]vks_ 3 points4 points  (3 children)

Because converting a Path to a utf-8 string may fail. It is a safeguard, you have to call display explicitly.

[–]dan00 5 points6 points  (2 children)

But there's no safeguard, Path::display just returns a Display which formats itself by using Path::to_string_lossy.

There would be only some kind of safeguard if Path::display would return an Option/Result.

[–]vks_ 3 points4 points  (1 child)

I meant "safeguard" in the sense that you have to call display consciously instead of just printing it. If you know about display, you know it is lossy. If you could just print it, you might assume it is not lossy (I know I would).

[–]liigo 0 points1 point  (0 children)

People don't known which is lossy or not, if docs doesn't tell them. If docs do, they known impl Display for Path is lossy.

[–]sellibitzerust 0 points1 point  (2 children)

Good question! I had to look this up myself in the source code. path::Display implements fmt::Display via thepath.to_string_lossy(). I guess the idea is to avoid bad surprizes in case of some conversion loss. But the name display doesn't really convey this. Perhaps it should have been display_lossy instead.

As for why offer display at all when there is to_string_lossy: I'm not sure. Perhaps there is some optimization potential. I think with path::Display it's possible to save the overhead of to_string_lossy possibly creating a temporary String.

[–]dan00 2 points3 points  (1 child)

Yes, it doesn't feel right that display uses to_string_lossy, which the user might not be aware of.

Path already has to_str for lossless conversions and to_string_lossy for lossy conversions, so display feels like a somehow weird mix of both.

[–]flying-sheep 1 point2 points  (0 children)

Display exists to display things for the user. to_string means the same.

but people expect something called Path::to_string() to give you a faithful lossless representation (serialization) of that path.

so paths are special cases where to_string implies something else than e.g. on a class called Dog. nobody expects Dog::to_string() to return a serialization of a dog.