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 a string?
- How to calculate the sum of a Rust slice?
- How to convert a Rust slice of u8 to u32?
- How to shift elements in a Rust slice?
- How to split a Rust slice?
- How to reverse a Rust slice?
- Does Rust perform bounds checking on slices?
- How to swap elements in a Rust slice?
- How to remove the last element of a Rust slice?
- How to push an element to a Rust slice?
More of Rust
- How to perform matrix operations in Rust?
- How to match whitespace with a regex in Rust?
- How to use regex lookahead in Rust?
- How to use regex to match a double quote in Rust?
- How to use a Rust HashMap in a struct?
- How to print the keys of a Rust HashMap?
- How to sort a Rust HashMap?
- How to replace strings using Rust regex?
- How to parse a file with Rust regex?
- Yield example in Rust
See more codes...