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 of u8 to u32?
- How to iterate over a Rust slice with an index?
- How to convert a Rust slice of u8 to a string?
- How to reverse a Rust slice?
- How to calculate the sum of a Rust slice?
- How to push an element to a Rust slice?
- How to slice a hashmap in Rust?
- How to check for equality between Rust slices?
- How to fill a Rust slice with a specific value?
- Does Rust perform bounds checking on slices?
More of Rust
- Rust YAML parser example
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to use regex lookbehind in Rust?
- How to convert a Rust HashMap to a struct?
- How to replace strings using Rust regex?
- How to replace all matches using Rust regex?
- How to ignore case in Rust regex?
- How to convert a u8 slice to a hex string in Rust?
See more codes...