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

Time:03-08

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.

CodePudding user response:

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",);

  • Related