Javatpoint Logo
Javatpoint Logo

What is a slice?

Slice is a data type that does not have ownership. Slice references a contiguous memory allocation rather than the whole collection. It allows safe, efficient access to an array without copying. Slice is not created directly but from an existing variable. A slice consists of the length, and it can be mutable or not. Slices behave like arrays only.

String slice

A string slice refers to a part of the string. Slice looks like:

Rather than taking an entire string, we want to take a part of the string. The [start..end] syntax is a range that begins at the start but does not include end. Therefore, we can create a slice by specifying the range within brackets such as [start..end] where 'start' specifies the starting position of an element and 'end' is one more than the last position in the slice. If we want to include the end of the string, then we have to use '..=' instead of '..'.

Diagrammatically representation:


Rust slices
  • If you want to start the index from 0, then we can drop the starting index also. It looks like:
  • If slice includes the last byte of the string, then we can drop the starting index. It looks like:

Let's see a simple example of string slice:

Output:

first word of the given string is javaTpoint

String slices are literals

String literals are stored in binary and string literals are considered as string slices only. Let's look:

The type of 'str' is '&str'. It is a slice pointing to a specific point of the binary. String literals are immutable, and '&str' is an immutable reference.

String slices as parameters

If we have a string slice, then we can pass it directly. Instead of passing the reference, we pass the string slice as a parameter to the function to make an API more general and useful without losing its functionality.

Other slices

An array can also be treated as slices. They behave similarly as a string slice. The slice has the type [&i32]. They work similarly as a string slice by storing a reference as a first element and length as a second element.

Consider a array:

Let's see a simple example.

Output:

Elements of 'a' array:
200
300
400

Next TopicWhat is struct




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials