rustHow to get an element from a slice in Rust?
To get an element from a slice in Rust, you can use the get method. This method takes an index as an argument and returns an Option<&T> where T is the type of the elements in the slice.
let v = [10, 40, 30];
let third: Option<&i32> = v.get(2);
println!("The third element is {:?}", third);
Output example
The third element is Some(30)
The code above does the following:
- Declares a slice
vwith three elements of typei32. - Calls the
getmethod onvwith the index2as an argument. - Prints the result of the
getmethod, which is anOption<&i32>.
Helpful links
Related
- How to convert a Rust slice to a fixed array?
- How to convert a Rust slice of u8 to a string?
- How to remove the last element of a Rust slice?
- How to reverse a Rust slice?
- How to shift elements in a Rust slice?
- How to split a Rust slice?
- How to iterate over a Rust slice with an index?
- How to push an element to a Rust slice?
- How to map a Rust slice?
- How to convert a Rust slice of u8 to u32?
More of Rust
- How to compare two Rust HashMaps?
- How to replace strings using Rust regex?
- How to match whitespace with a regex in Rust?
- How to use regex to match a group in Rust?
- How to get a capture group using Rust regex?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to replace a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to perform matrix operations in Rust?
- How to use captures_iter with regex in Rust?
See more codes...