DEV Community

Discussion on: How to write a Stack in Rust

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 ;)