Another question regarding &'static str

Hi folks

I read the post from (Quick Question: &'static str - #6 by kornel) and it was useful for me to understand the topic discussed.

I have another question regarding that. In a tutorial (Rust - Generic Types), I see the following snippet

struct Book {
   name:&'static str,
   id:u32
}

If I removed the &, the code won't compile, why is that the case?

str is a dynamically sized type (DST). Those can only be used behind some sort of indirection, like a reference in your case, or some other pointer type, like Box or Arc. You can make your Book struct a DST to by putting name as the last field of the struct.

Edit: after playing around with this and trying to construct a Book with a str as the last field using unsized coercion (currently the only way to construct a DST), I'm not exactly sure how to unsize something into a str. You can unsize an array into a slice, but I don't know what we can unsize into str.

3 Likes

Thanks for the explanation.

1 Like

AFAIK there is no safe way. Here's an unsafe way.

1 Like

Your answer got me interested in whether a str with non-valid utf-8 is UB or not and interestingly enough, miri did not complain. But beware of trying to print a non utf-8 str, it will kill your playground :smile:

There was an explicit decision to make it library-UB but not instant-UB.

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.