I want to create a Wrapper around an existing type/struct. According to the Newtype pattern, as per Rust Book ch 19, "implementing Deref trait on the Wrapper to return an inner type would give access to all the underlying methods":
https://doc.rust-lang.org/book/ch19-03-advanced-traits.html
Here is my implementation on a wrapper around a String. A simplified example:
struct Wrapper(String);
impl Deref for Wrapper {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0 //pointer to Inner value
}
}
However, calling a method which consumes self throws an error:
fn main() {
let d = "Dog".to_string();
let w = Wrapper(d);
w.into_bytes();
}
Error: cannot move out of dereference of Wrapper move occurs because value has type std::string::String, which does not implement the Copy trait
Therefore I have two questions:
- What is wrong with my implementation and how do make it work?
- I'd like to make it work properly with self, &self, mut self, &mut self methods. How do I also implement DerefMut appropriately?