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 of u8 to u32?
- How to convert a u8 slice to a hex string in Rust?
- How to convert a Rust slice of u8 to a string?
- How to get the last element of a Rust slice?
- How to convert a Rust slice to a fixed array?
- How to convert a slice of bytes to a string in Rust?
- How to convert a slice to a hex string in Rust?
- How to convert a vector to a Rust slice?
- How to calculate the sum of a Rust slice?
- How to create a slice from a string in Rust?
More of Rust
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to replace strings using Rust regex?
- How to convert struct to bytes in Rust
- How to use Unicode in a regex in Rust?
- How to match a URL with a regex in Rust?
- How to zip two vectors in Rust?
- How to loop through enum in Rust
- How to parse a file with Rust regex?
See more codes...