cognitive-engineering-lab / rust-book

The Rust Programming Language: Experimental Edition
https://rust-book.cs.brown.edu
Other
503 stars 82 forks source link

string slice vs string literal #175

Closed block0xhash closed 1 week ago

block0xhash commented 3 months ago

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 theto_string() method which is available to a string literals because they implement the Display trait.

So in the code below variable datais indeed a string literal because we are calling data.to_string() image

however s2 below is referred to as a string slice, which is used after appending its contents to a string ? image

is s2not a string literal just like data ?

are string literals and string slices the same thing ?

twhentschel commented 2 months 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.

willcrichton commented 1 week ago

@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.