Associated constant with anonymous generic type

I have this trait:

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 :confused: 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.

1 Like

You might as well declare your constant as a non-generic &Path,

pub trait DefaultFile {
    const DEFAULT_FILE: &Path;
}

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.
2 Likes

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.

If you use a const at all, then the lifetime of the reference will always be 'static, so there will not be any lifetime parameters needed.

2 Likes

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.

2 Likes

(Not relevant to the topic but you can have non-'static consts.)

I should have said: the lifetime of the reference will always be able to be 'static.

1 Like