Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a static String in Rust? [duplicate]

Tags:

string

rust

Is there a way I can create a static String in Rust?

I tried this:

static somestring: String = String::new();

but I got this error:

error: `std::string::String::new` is not yet stable as a const fn
 --> src/main.rs:2:29
  |
2 | static somestring: String = String::new();
  |

How to create a static string at compile time does not solve my problem because it's about &'static str, not String. I need the String to be globally addressable.

like image 323
LJ Germain Avatar asked May 25 '26 23:05

LJ Germain


1 Answers

Don't confuse the String type with the str type.

What are the differences between Rust's `String` and `str`?

A String is mutable and always heap-allocated.

A str, usually presented as &str is not mutable and is simply a view into a string.

Your question seems to confuse the idea of static and globally adressable. You may refer to (&'static str) as a string with a 'static lifetime. Strings with 'static lifetimes are common because they (mostly) represent hardcoded strings in the program. A 'static lifetime means the object (in this case, a string) will live until the end of the program. Most 'static objects are known at compile time. This should be natural to think about, because hardcoded strings are known at compile time. These strings can not mutate.

Strings on the other hand, are mutable. And you can make a String from a &'static str.

Given the lack of context in the question, if what you want is a String that is globally adressable and want to define it static I may suggest the macro lazy-static:

https://crates.io/crates/lazy_static

As sugested by mcarton, this question seems to boil down to the singleton pattern. You can learn more about its implementation in Rust here: How do I create a global, mutable singleton?

like image 150
Josep Avatar answered May 27 '26 13:05

Josep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!