Newtype Pattern - Replicate methods of inner value or expose inner value?

Hello,
I'm using the newtype pattern to represent a n times 64 binary matrix by a Vec of length n. I need some functionality of the inner value (the Vec) to be accessible from outside, e.g. len() or swap(). Should I keep the Vec private and replicate all those methods in my new type and delegate them to the Vec, or is it better to expose the Vec by an as_inner() method or something similar? With "better", I mean what is more commonly used / more idiomatic.
Best regards,
Finn Rudolph

It depends on whether you can afford allowing arbitrary manipulation of the inner value. If you can, then you can just expose it. I don't recommend a custom method, though – use AsRef/AsMut or Borrow/BorrowMut or Deref/DerefMut for this purpose.

If your newtype enforces additional invariants (e.g. that the Vec is always sorted), then you must not expose it mutably.

3 Likes

A good question is which of these.

As much as I hate AsRef (for having issues with smart pointers and impls in the standard library), I feel like AsRef is the best choice to "reinterpret" a new type as the inner type.

Borrow puts additional constraints on how the returned value behaves, so it's often contrary to the concept of a newtype.

Deref should only be used when the outer type acts like a pointer to the inner type, so this also usually doesn't fit the idea of a newtype pattern, I think.

2 Likes

Hi guys

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.