Copyable immutable string?

Is that possible to put string behind some kind of a primitive to get a structure which is copyable assuming the string is immutable?

#[derive(Copy, Clone)]
pub struct IdentityByName(Box<str>);


The type &str is Copy.

It's not possible if you want the string to be owned.

1 Like

How to spell it without a lifetime?

Not having a lifetime annotation is exactly what "owned" means, so you can't.

(except for &'static str, but that requires leaking the memory containing the string, or hardcoding it in your source code)

1 Like

What problem are you trying to solve?

Will the shared string be deallocated at the end at a known time? Use &'a str with the appropriate lifetime.

Do you want to keep track of the number of references at runtime, and deallocate the memory once the count goes to 0? Use Rc<str>.

Will the string never get deallocated? Use &'static str.


It makes sense. Thanks.

It makes sense, but Rc is not Copy.

Why do you need your type to be Copy?

To don't bother with clone. To work with instances of the type as with primitives. 'static str + leaking + arena seems a way to go.

How about ArrayString in arrayvec - Rust ?
It's Copy and great for small strings.

1 Like

Thanks. I have been thinking about that, but it is much more than single machine word. It's not efficient to rotate so big structure in the stack in my case.

If the strings are stored in some sort of arena, you will want to use &'a str where 'a is the arena lifetime, rather than &'static str



Easiest solution is to write your own static string:

pub struct StrBuf<const N: usize> {
    inner: [mem::MaybeUninit<u8>; N],
    len: u8,

And interface to get &str via AsRef or something
You can make such static string copyable just fine (note that it is not really efficient if string is big)

1 Like

Hi. Sounds like the same solution as using arrayvec::ArrayString. No?

Well true that, it is the only proper solution if you want owned string

1 Like

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.