How to convert a usize into an index (usize -1) of the last item in a vector

Hi,

I have:
let blocks: Vector;

I want to find the index of the last one.

I want to say:

let last: u64 = Blocks.len(); // gives me a usize

how do I get the type conversion?

Vectors are indexed by usize. There's no need for any type conversion. You can get the index of the last element by subtracting 1 from the length.

1 Like

You can .last() at the Vec<T> to get Option<&T>, which gives None if the vector is empty. If you want to mutate it you can use .last_mut() instead.

https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.last

https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.last_mut

Thanks both for the suggestions.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.