use std::path::Path;
/// Trait for types with a default file path.
pub trait DefaultFile {
/// The type of the default file path.
type DefaultFile: AsRef<Path>;
/// The default file path.
const DEFAULT_FILE: Self::DefaultFile;
}
I find this definition and subsequent usage a bit verbose.
However, I could not get anything like this to work:
use std::path::Path;
/// Trait for types with a default file path.
pub trait DefaultFile {
/// The default file path.
const DEFAULT_FILE: impl AsRef<Path>;
}
Is there a short-hand for this kind of definition?
Given that impl trait in associated types is itself still unstable, I wouldn’t think so What you can do is use return type impl trait with an associated function rather than a constant, but then you of course can’t yet use it in const contexts on stable.
because you aren’t going to be able to do much of anything else with impl AsRef<Path> even if it were allowed:
It’s impossible to create a constant non-empty PathBuf.
An implementation of the trait could use &str instead of &Path, but nobody can make use of that if the trait doesn’t have the associated type, except by calling AsRef<Path>, which just gives &Path.
An implementation could use a custom type that implements AsRef<Path>, but again, nobody can make use of the type in any way.
These are good points, but I want the implementor to be able to use anything that may be used as a &Path. Introducing &Path as the type will force me to add a lifetime parameter to the trait and subsequently to all its subtraits.
True. One issue I am facing is, that some implementors use &'static str for the type.
Is there a way to const-convert a &'static str into a &'static Path?
Yes, of course, that’s what Path::new() is for — wait. That function is not const fn. There doesn’t seem to be a way to construct a Path in const context at all. Ugh.
You may have to use &str as the type of your constant.