Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Rust Slices


Share

Slices

A slice lets you use a part of a string or a list of values, without copying it.

For example, from the text "Hello World" you can take a slice with only "Hello". The slice borrows the text, just like a reference: it only looks at the original data.


String Slices

To create a slice, write & and the variable name, followed by a range in square brackets: [start..end]:

Example

let text = String::from("Hello World");
let hello = &text[0..5];
let world = &text[6..11];

println!("{}", hello);
println!("{}", world);
Try it Yourself »

Just like in a for loop, the start index is included, and the end index is not. The first character has index 0:

CharacterHello(space)World
Index012345678910

&text[0..5] takes index 0 to 4 ("Hello"), and &text[6..11] takes index 6 to 10 ("World").


Leave Out the Start or End

If the slice starts at the beginning, you can leave out the first number. If it goes to the end, you can leave out the last number. With no numbers, the slice is the whole string:

Example

let text = String::from("Hello World");

println!("{}", &text[..5]);
println!("{}", &text[6..]);
println!("{}", &text[..]);
Try it Yourself »


You Already Know &str

The &str type, which you have used since the Data Types chapter, is a string slice. A text in double quotes, like "Hello", is a slice of text that is stored inside your program.

That is why a function with a &str parameter works with both a text in quotes and a slice of a String:

Example

fn greet(name: &str) {
  println!("Hello, {}!", name);
}

fn main() {
  greet("Liam");

  let full_name = String::from("Jenny Smith");
  greet(&full_name[..5]);
}
Try it Yourself »

Array Slices

Slices also work with arrays. An array is a list of values in square brackets, which you will learn more about in the Arrays chapter. Use {:?} to print all values of a slice:

Example

let numbers = [10, 20, 30, 40, 50];
let middle = &numbers[1..4];

println!("{:?}", middle);
println!("{}", middle.len());
Try it Yourself »

Slices as Function Parameters

A function that takes a slice (&[i32]) can work with a whole array, or with just a part of it:

Example

fn sum(numbers: &[i32]) -> i32 {
  let mut total = 0;
  for n in numbers {
    total += n;
  }
  total
}

fn main() {
  let scores = [3, 7, 5, 9];

  println!("{}", sum(&scores));
  println!("{}", sum(&scores[..2]));
}
Try it Yourself »

sum(&scores) adds all four numbers. sum(&scores[..2]) only adds the first two: 3 + 7.


Out of Range

If the range goes past the end of the string, the program stops with an error:

Example

let text = String::from("Hello World");
let part = &text[0..20]; // Error
println!("{}", part);
Try it Yourself »

The text "Hello World" has 11 characters, so the end index can be at most 11.

Note: String slice indexes count bytes, not characters (see String Methods). For English letters, one character is one byte, so the indexes are the same.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.