jon
January 10, 2025, 6:11pm
1
Heya,
I can do
fn main() {
const ABC1: &str = "abc";
static ABC2: String = String::new();
}
but it seems that other strings can't be defined.
fn main() {
const ABC3: &OsStr = OsStr::new("abc");
const ABC4: OsString = OsString::new();
const ABC5: &Path = Path::new("abc");
const ABC6: PathBuf = PathBuf::new();
}
Or could you please advise some workaround?
Thank you.
If there is no const fn
method to construct an object, then it can't be stored in a constant. But it can be stored in a static variable using OnceLock .
2 Likes
Also if you're doing this inside main
, let
works fine for most things.
1 Like
jon
January 10, 2025, 6:36pm
4
I wanted to do that in a root of a module. I'll most likely just use a normal string and then OsStr::new(CONSSTRING)
when needed.
Thank you.
OsStr::new
and Path::new
take an AsRef
and traits can’t yet be used in const
OsString::new
and PathBuf::new
could presumably be const, but there aren’t many uses for an empty string that you cannot modify.
Won't work for const, but if static, LazyLock is an option:
use std::sync::LazyLock;
static STRING: LazyLock<OsStr> = LazyLock::new(|| OsStr::new("abc"));