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>);
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.
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)
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.
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
Oh.
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)
Well true that, it is the only proper solution if you want owned string
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.