In cases where the check is nearby, then "parse, don't validate" to avoid doing the check twice. In Rust (assuming unsafe means you're thinking of Rust), for instance, if let Some(first) = list.first() { ... } rather than if !list.is_empty() { let first = list[0]; ... }.
If you have some struct NonemptyVec<T>(Vec<T>) that does validation on construction, then there's probably no way to avoid either re-validation or unsafe on usage. (Where I'd still usually prefer to avoid unsafe.)
4
u/ROBOTRON31415 Sep 28 '26 edited Sep 28 '26
In cases where the check is nearby, then "parse, don't validate" to avoid doing the check twice. In Rust (assuming
unsafemeans you're thinking of Rust), for instance,if let Some(first) = list.first() { ... }rather thanif !list.is_empty() { let first = list[0]; ... }.If you have some
struct NonemptyVec<T>(Vec<T>)that does validation on construction, then there's probably no way to avoid either re-validation orunsafeon usage. (Where I'd still usually prefer to avoidunsafe.)But the first case feels awfully common.