How to constrain types where `AsRef` and `AsMut` point to the same data?
⚓ Rust 📅 2026-05-18 👤 surdeus 👁️ 2During my Rust experience, I often declare a function, which takes a generic variable which implements both AsRef<[u8]> and AsMut<[u8]>. Under this constraint, I can access the data both uniquely or sharedly.
However, I realized that the AsRef and AsMut trait does not enforce that the as-ed data is the same. For example:
struct Foo { a: [u8; 4], b: [u8; 8], }
impl AsRef<[u8]> for Foo {
fn as_ref(&self) -> &[u8] { &self.a }
}
impl AsMut<[u8]> for Foo {
fn as_mut(&mut self) -> &mut [u8] { &mut self.b }
}
If AsRef and AsMut point to different data, a lot of logic in my code will break.
The same situation also holds for Deref/DerefMut (DerefMut is restricted to re-use the Target associated type of Deref, which I guess the design is to imply that they should point to the same data), Borrow/BorrowMut.
P.S. Directly declare the function to take a Box<[u8]> does not work, since this function can also takes Memmap, a buffer created by mmap. Converting it to Box will lose the destructor.
12 posts - 5 participants
🏷️ Rust_feed