‹ BackHN Continuity

Thread

Rusty thoughts on "Parse, don't validate"

95 points · 47 comments · ingve

  1. Fluorescence · · focus · HN ↗
    Not sure that type is good advice:

        pub struct NonEmpty<T> {
            pub head: T,
            pub tail: Vec<T>,
        }
    
    You'd have to manually implement the traits to support the ergonomics of slices and iteration and costly reallocation if you need to pass ownership as a Vec:

    I'd expect:

        pub struct NonEmpty<T> {
            v: Vec<T>,
        }
    
    The constructor would enforce the invariant and then you'd impl Deref and DerefMut for [T] to gain normal len/is_empty/indexing/iteration, passing as &[T] to other funcs and mutating values (which can't break the invariant).

    To mutate length while preserving the invariant it's dealers choice e.g.

    - add .into_vec() for unwrap/mutate/rewrap

    - add invariant preserving mutators of your choice

    1. shim__ · · focus · HN ↗
      DerefMut would allow you to call `clear()` on `v` violating the invariant

      I'd be great is there were a way to shadow methods but even then guarantees would be poor since Vec might add a new method in the future which isn't covered by invariant checks

      1. Fluorescence · · focus · HN ↗
        clear() is a method of std::Vec not std::slice.

        DerefMut to [T] not Vec<T>.

Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.