Slice syntax
- Rust course
- Beginner
- Lesson 55/115
- 4 min
Learn the [a..b] and [a..] slice syntax.
Slice syntax
The ends of the range can be omitted:
let s = "abcdef";
&s[..3] // "abc" (from start to 3)
&s[3..] // "def" (from 3 to end)
&s[..] // "abcdef" (all of it)
&s[1..=2] // "bc" (2 included)a..b excludes b, a..=b includes it. &s[..] is one way to turn a String into a &str.
Bounds checking
Going out of bounds panics: &"abc"[1..5] stops with "byte index 5 is out of bounds". It also panics if the start is greater than the end. If you don't want a panic, use get; it returns an Option:
let s = "abc";
println!("{:?}", s.get(0..2)); // Some("ab")
println!("{:?}", s.get(1..5)); // NonePractice Three slices
For let s = "abcdef";, print the slices &s[..3], &s[3..] and &s[1..=2] on one line separated by spaces.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let s = "abcdef";
println!("{} {} {}", &s[..3], &s[3..], &s[1..=2]);
}Expected output
abc def bc
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is <code>&"abcdef"[2..=4]</code>?
- "bcde"
- "cde" Correct answer
- "cd"
- "bcd"
Explanation: Bytes 2, 3 and 4 are taken: c, d, e.
2 To the end
let s = "abcdef";
let son = &s[____]; // "def"
let s = "abcdef";
let son = &s[3..]; // "def"
Explanation: The range 3.. goes from byte 3 to the end.
3 Range and result on "abcdef"
| Term | Meaning |
|---|---|
[..3] |
"abc" |
[3..] |
"def" |
[1..=2] |
"bc" |
[..] |
"abcdef" |