logoalt Hacker News

Fluorescence • today at 5:16 PM • 1 reply • view on HN

Deref/DerefMut enables implicit type coercion rather than exposing an interface. You can choose the target type and immutable/mutable but not parts of the target type.

You can use all the slice reference methods (that do not require ownership) with:

    impl<T> Deref for NonEmpty<T> {
        type Target = [T];

        fn deref(&self) -> &Self::Target {
            &self.v
        }
    }

    impl<T> DerefMut for NonEmpty<T> {
        fn deref_mut(&mut self) -> &mut [T] {
            &mut self.v
        }
    }
https://doc.rust-lang.org/std/primitive.slice.html

If you DerefMut to a Vec then you won't be able to preserve the invariant.

If you want control over methods to expose then you need wrapper methods for those you want. If you want to expose some of the traits the inner type implements then there are likely derive macros available e.g. with derive_more you could expose just indexing as:

    #[derive(Index, IndexMut)]
    struct MyVec(Vec<i32>);

Replies

eptcyka • today at 7:37 PM

The reason I am asking is because I strongly believe to achieve the semantics of the type, just derefing to a Vec will not be sufficient.