Transmuting &’a str to &’static str

Hey there! I know transmuting &’a to &’static isn’t ok and is UB, I don’t really know why it doesn’t work correct though. (I tried to get &’static str from String.trim() but the output was incorrect)

So, maybe I don’t know something about how references really work internally?

What is your question?

Here's how it works with the current compiler: You can use the &'static str until the next time you modify the String (destructor counts as modification). Any uses after the next modification can cause all sorts of bad stuff.

1 Like

Sorry for wasting your time, I understood my problem. Error occurred because my &’static referred to a dropped value. Now I think I can call core::mem::forget before transmuting :wink:

If you really need to make an &'static str from a String you can do something like this

fn to_static(s:String)->&'static str {

That's a relatively odd need, though, and suggests that there are some potential design improvements in the rest of your code.


Lifetimes don't tell the compiler what to do. They explain what the code actually does.

If you transmute a string to 'static lifetime, without changing the code to leak the memory to guarantee it having this lifetime for real, you're lying to the compiler and creating a safety bug. The compiler can't make references live longer.

If you've got a compilation error telling you to use 'static lifetime, it's misleading. It's trying to say that all temporary references are forbidden, and simply won't work, and there's no way to make them work.


Yeah, thx you but I’ve already found the way to perform my minds and probable problems :slight_smile:

UPD: I’ll mark your answer as solution. Don’t want anybody to reply anymore.

This post was flagged by the community and is temporarily hidden.

It looks like this has been answered and is starting down an unproductive path. Closing.

1 Like