DEV Community

Discussion on: How to write a Stack in Rust

Collapse
 
lain8dono profile image
Lain-dono

Instead of Vec::get you can use Vec::last.

Collapse
 
precosmicowl profile image
Kirill Vasiltsov

I didn't know that! Thanks!

Collapse
 
elshize profile image
Michał Siedlaczek

Yes, especially since self.length() - 1 will straight up panic if the stack is empty, while Vec::last will return None. The reason is that self.length() - 1 will try to subtract 1 from an unsigned integer equal to 0. To correct it, you could use wrapping_sub, then it would work correctly by returning None for the index usize::MAX. But of course, the way to do it is to use last ;)