Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do I need to use &str when defining a string literal in Rust?

Why can I not use str here?

let question: &str = "why";

What’s the difference between str and &str?

I get that & denotes a reference, but I’m confused about what &str is referencing.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A str is a sequence of UTF-8 encoded bytes of unknown length, somewhere in memory.

Because its size is not known at compile time, it can’t be put on the stack directly, instead, a reference must be used.

A string literal (i.e. the "why" syntax) creates a space in the data segment of the binary, and returns a reference to that location, which is an &str (in particular, an &'static str, because it is never dropped).

If you write let question: str = "why";, this won’t compile for the same reason: let i: i32 = &123; won’t compile.

P.S. ("hello") is not a tuple, it is just a &str in brackets. If you want to make a tuple with a single element, add a trailing comma: let hello: (&str,) = ("hello",);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading