jonhoo / atone

A `VecDeque` (and `Vec`) variant that spreads resize load across pushes.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unnecessary unwrap ?

hanako-eo opened this issue · comments

commented

When I navigate in the code I see in the method in CustomVc at the line 235 in lib.rs

    pub fn last(&self) -> Option<&T> {
        let len = self.len();
        if len == 0 {
            None
        } else {
            Some(self.get(len - 1).unwrap())
        }
    }

but why all of that ? You can just write

pub fn last(&self) -> Option<&T> {
    let len = self.len();
    if len == 0 {
        None
    } else {
        self.get(len - 1)
    }
}

(and same thing with the last_mut)

Ah, it is written this way essentially to be defensive — the get should not fail. If the code was written the way you propose, then it could silently start failing if, say, the len == 0 clause was changed somehow. In this small code snippet the risk of that is pretty minor, but as a general rule I like the more verbose variant because it represents an asset.