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
v
with three elements of typei32
. - Calls the
get
method onv
with the index2
as an argument. - Prints the result of the
get
method, which is anOption<&i32>
.
Helpful links
Related
- How to convert a Rust slice to a fixed array?
- How to iterate over a Rust slice with an index?
- 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 to a string?
- How to convert a Rust slice to a tuple?
- How to declare a Rust slice?
- How to swap elements in a Rust slice?
- How to convert a vector to a Rust slice?
- How to convert a slice into an iter in Rust?
More of Rust
- How to use regex to match a double quote in Rust?
- How to use regex with bytes in Rust?
- How to perform matrix operations in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to match the end of a line in a Rust regex?
- How to use regex captures in Rust?
- How to add matrices in Rust?
- How to multiply matrices in Rust?
- How to parse JSON string in Rust?
- How to replace a capture group using Rust regex?
See more codes...