String slices
- Rust course
- Beginner
- Lesson 54/115
- 4 min
Reference part of a string with &str slices.
String slices
A slice is a reference to a contiguous part of a collection; it doesn't take ownership. A string slice has the type &str and is taken with a byte range:
let s = String::from("merhaba dünya");
let ilk = &s[0..7]; // "merhaba"
let son = &s[8..]; // "dünya"
println!("{ilk} / {son}");The range is in byte positions, not characters. "ü" takes two bytes, so "dünya" is 6 bytes.
Why are slices safe?
Because a slice borrows its source, the source can't be changed while the slice is alive:
let mut s = String::from("rust dili");
let kelime = &s[0..4];
// s.clear(); // error E0502: kelime is still going to be used
println!("{kelime}");So the bug of an index pointing into a cleared source is caught at compile time. String literals ("merhaba") are in fact &str slices embedded in the program.
Practice Two pieces
For let s = String::from("rust dili");, take the slices &s[0..4] and &s[5..] and print them with | between.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let s = String::from("rust dili");
let a = &s[0..4];
let b = &s[5..];
println!("{}|{}", a, b);
}Expected output
rust|dili
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens with <code>let s = String::from("çay"); let x = &s[0..1];</code>?
- Compile error
- x = ""
- Runtime panic: 1 is not a char boundary Correct answer
- x = "ç"
Explanation: "ç" is two bytes; byte 1 falls in the middle of a character and slicing panics.
2 First four bytes
let s = String::from("rust dili");
let ilk = &s[____];
let s = String::from("rust dili");
let ilk = &s[0..4];
Explanation: The range 0..4 takes bytes 0, 1, 2, 3: "rust".
3 Expression and result
| Term | Meaning |
|---|---|
&s[0..7] |
"merhaba" |
&s[8..] |
"dünya" |
"çay"[0..1] |
Panic |
"dünya".len() |
6 |