tshepang
tshepang

Reputation: 12459

How to run PathBuf::new with an argument

Given:

PathBuf::new("foo.txt")

I get an error:

this function takes 0 parameters but 1 parameter was supplied [E0061]

Shouldn't it work, given that the method with the argument is listed in the API documentation, under he section Methods from Deref. The few methods I've checked from that section work with PathBuf.

Upvotes: 2

Views: 429

Answers (2)

Vladimir Matveev
Vladimir Matveev

Reputation: 127771

While it is indeed not possible to call Path::new() method over a PathBuf because it is static, the correct way to obtain a PathBuf from a string is just to use the generic conversion:

let p: PathBuf = "foo.txt".into();

This is possible because PathBuf implements From for everything which can be converted to a reference to OsStr:

impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf

And &str does implement AsRef<OsStr>.

Upvotes: 3

Francis Gagn&#233;
Francis Gagn&#233;

Reputation: 65742

The methods listed under Methods from Deref are only applicable when calling methods on a PathBuf object. This section describes methods that are implemented on Path, but that are available thanks to the Deref<Target=Path> trait implementation on PathBuf.

The new method does not take self as an argument, so Deref does not apply (I think it's a bug that this method is listed here). I suspect you did not pay attention to the method's signature: it returns a &Path, not a PathBuf. That would have told you that the method is unrelated to PathBuf.

Upvotes: 3

Related Questions