Putting a `String` in a const

Is there any way to make a constant holding a String? E.g., something like this

const FOO: String = String::from("foo");

except this fails because String::from is not a const fn.

Creating a new (nonempty) String allocates memory on the heap, which is not possible in a const context. Does &'static str not work for your use-case?

Yeah, that makes sense. I think I might just use a static variable instead (I want to avoid unnecessary allocations).

The alternative, which allows you to do heap allocations or pretty much arbitrary work in a "constant"-like thing, is lazy_static which uses some atomic variables and clever usages of Deref to run the initialization code the first time you access it. Of course, in this case, a const FOO: &'static str = "foo"; would be much lighter and simpler.

1 Like

I recently learned that one can elide the explicit 'static lifetime in a const definition, e.g. const FOO: &str = "foo"; feels even “lighter” :wink:

1 Like

Oh, yes! I think that was added within the past few years. It's nice.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.