Why can I not use
let question: &str = "why";
What’s the difference between
I get that
& denotes a reference, but I’m confused about what
&str is referencing.
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.
("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",);
Answered By – cameron1024
Answer Checked By – Pedro (BugsFixing Volunteer)