Slices
Borrowed views.
Slices is a free Learn Rust Coding lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is a Slice?
A slice is a borrowed view into a contiguous part of a collection. It does not own data — it points into existing data.
Slices are written with a range inside brackets.
fn main() {
let arr = [1, 2, 3, 4, 5];
let part = &arr[1..4];
println!("{:?}", part);
}Slice Range Syntax
Ranges select a start and end index. The end is exclusive.
&v[1..4]— indices 1, 2, 3.&v[..3]— from start to 3.&v[2..]— from 2 to the end.
fn main() {
let v = vec![10, 20, 30, 40];
println!("{:?}", &v[..2]);
println!("{:?}", &v[2..]);
}String Slices
A string slice &str is a view into part of a String. Index ranges are by byte position.
fn main() {
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
println!("{} {}", hello, world);
}Whole-Collection Slices
Use &v[..] to slice the entire collection. This is how a Vec borrows as a slice.
fn main() {
let v = vec![1, 2, 3];
let whole = &v[..];
println!("{:?}", whole);
}Slices as Parameters
Functions that take &[T] accept both arrays and vectors. This makes them flexible.
fn sum(items: &[i32]) -> i32 {
let mut total = 0;
for x in items {
total += x;
}
total
}
fn main() {
let v = vec![1, 2, 3];
let a = [4, 5, 6];
println!("{} {}", sum(&v), sum(&a));
}Slices Borrow, Not Own
Because a slice borrows, the original collection must stay alive while the slice is used. The compiler enforces this.
fn main() {
let v = vec![100, 200, 300];
let s = &v[0..2];
println!("slice {:?}, original {:?}", s, v);
}Slice Length
Like other collections, slices have a len() method giving the number of elements they cover.
fn main() {
let v = vec![5, 6, 7, 8, 9];
let middle = &v[1..4];
println!("length {}", middle.len());
}first and last
Slices provide first() and last(), returning Options so empty slices are handled safely.
fn main() {
let data = [10, 20, 30];
let s = &data[..];
println!("{:?} {:?}", s.first(), s.last());
}Iterating a Slice
You can iterate over a slice just like any collection.
fn main() {
let v = vec![1, 2, 3, 4];
for x in &v[1..3] {
println!("{}", x);
}
}A First-Word Function
A common slice use case: returning a slice into existing text, like the first word of a sentence.
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &b) in bytes.iter().enumerate() {
if b == b' ' {
return &s[0..i];
}
}
s
}
fn main() {
println!("{}", first_word("hello there"));
}Why Slices Are Safe
Slices avoid copying data while preventing dangling references. The borrow checker guarantees the underlying data outlives the slice.
fn main() {
let words = vec!["a", "b", "c", "d"];
let pair = &words[1..3];
println!("{:?}", pair);
}Quick Check
Recall what a slice represents.
Recap
Slices in Rust:
- A borrowed view:
&v[start..end], end exclusive. &stris a string slice;&[T]is an array/vector slice.- Slice parameters accept both arrays and vectors.
- The borrow checker keeps slices safe.
fn average(nums: &[i32]) -> i32 {
nums.iter().sum::<i32>() / nums.len() as i32
}
fn main() {
let v = vec![4, 8, 12];
println!("{}", average(&v[..]));
}Frequently asked questions
Is the “Slices” lesson free?
Yes — the full text of “Slices” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Slices”?
Borrowed views. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Slices” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.