Closed block0xhash closed 1 week ago
According to this stackoverflow answer, a string literal is just a &'static str
, so it's a string slice but with a static lifetime.
Edit: also this is discussed a little further down in the book in 10.3 The Static Lifetime:
All string literals have the 'static lifetime, which we can annotate as follows:
let s: &'static str = "I have a static lifetime.";
note: I'm still learning so I may be wrong.
@twhentschel's answer is correct. To be more precise, all string literals are string slices, but not all string slices are string literals. For example:
let s = String::from("foo");
let s_ref: &str = &s;
In this case, the expression &s
is a string slice, but not a string literal.
In https://rust-book.cs.brown.edu/ch08-02-strings.html I am finding the interchangable use of string slice and string literal to be a tricky
let data = "initial contents"; // is referred to as a string literal
further down we are saying:
let s2 = "bar"; // is referred to as a string slice
below we are creating a string from a string literal using the
to_string()
method which is available to a string literals because they implement theDisplay
trait.So in the code below variable![image](https://github.com/cognitive-engineering-lab/rust-book/assets/16897613/47210522-596d-45cc-a054-22e8073b7f35)
data
is indeed a string literal because we are callingdata.to_string()
however![image](https://github.com/cognitive-engineering-lab/rust-book/assets/16897613/1392fc69-d946-4d06-b0e4-9d5bc71d11f1)
s2
below is referred to as a string slice, which is used after appending its contents to a string ?is
s2
not a string literal just likedata
?are string literals and string slices the same thing ?