rustHow to get the last element of a slice in Rust?
The last element of a slice in Rust can be obtained using the .last()
method. This method returns an Option<&T>
where T
is the type of the elements in the slice.
Example code
let v = [1, 2, 3];
let last = v.last();
Output example
Some(&3)
The .last()
method returns an Option<&T>
which is an enum with two variants: Some(&T)
and None
. If the slice is empty, None
is returned, otherwise Some(&T)
is returned where T
is the type of the elements in the slice.
Helpful links
Related
- How to calculate the sum of a Rust slice?
- How to convert a Rust slice to a fixed array?
- How to convert a Rust slice of u8 to a string?
- How to push an element to a Rust slice?
- How to convert a slice of bytes to a string in Rust?
- How to align a Rust slice to a specific size?
- How to convert a vector to a Rust slice?
- How to convert a Rust slice to a tuple?
- How to convert a Rust slice to a struct?
- How to convert a Rust slice to a string?
More of Rust
- How to declare a constant HashSet in Rust?
- How to borrow with lifetime in Rust
- How do I get the last character from a string in Rust?
- Bitwise XOR operator usage in Rust
- How do I determine the size of a variable in Rust?
- How to convert struct to protobuf in Rust
- How do I share a variable between structs in Rust?
- How do I convert a string to bytes in Rust?
- rust string doc
- Using Rust box in struct
See more codes...