---
title: "What is a slice in Rust and how is it different from an array?"  
description: "What is a slice in Rust and how is it different from an array?"  
author: "Revati S Misra"  
published: 2023-06-19  
updated: 2023-06-20  
canonical: https://www.mindstick.com/forum/158783/what-is-a-slice-in-rust-and-how-is-it-different-from-an-array  
category: "rust"  
tags: ["programs", "rust"]  
reading_time: 2 minutes  

---

# What is a slice in Rust and how is it different from an array?

What is a [slice](https://answers.mindstick.com/qa/115838/how-to-play-and-enjoy-slice-master-a-fun-experience-worth-trying) in [Rust](https://www.mindstick.com/forum/160170/explain-rust-s-ownership-borrowing-and-lifetimes-system) and how is it different from an [array](https://www.mindstick.com/articles/335/jagged-array-in-c-sharp-dot-net)?

## Replies

### Reply by Aryan Kumar

In Rust, a slice is a reference to a contiguous sequence of elements of a particular type. Slices are dynamically sized, meaning that they can be any length. Arrays, on the other hand, are statically sized, meaning that their length is known at compile time.

Here is an example of how to create a slice:

Rust

```plaintext
let slice = &[1, 2, 3];
```

The slice variable is a reference to the first three elements of the array [1, 2, 3]. The & operator indicates that the slice variable is a reference.

Here is an example of how to use a slice:

Rust

```plaintext
let sum = slice.iter().sum();
```

The iter() method on the slice variable returns an iterator over the elements of the slice. The sum() method on the iterator returns the sum of the elements of the iterator.

Here is the difference between a slice and an array:

| Feature | Slice | Array |
| --- | --- | --- |
| Size | Dynamic | Static |
| Reference | Yes | No |
| Creation | &[T] | [T; N] |
| Use | Borrowing a sequence of elements | Owning a sequence of elements |

Here are some of the benefits of using slices:

- **Flexibility:** Slices can be any length, which makes them more flexible than arrays.
- **Performance:** Slices are more performant than arrays, because they do not need to copy the data when they are passed to functions.
- **Safety:** Slices are safer than arrays, because they cannot be used to access out-of-bounds elements.

If you are looking for a way to borrow a sequence of elements in Rust, I recommend using slices.


---

Original Source: https://www.mindstick.com/forum/158783/what-is-a-slice-in-rust-and-how-is-it-different-from-an-array

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
