我想围绕现有类型/ struct 创建一个包装器.根据新类型模式,根据Rust Book ch 19,"在包装器上实现Deref-trait以返回内部类型将提供对所有底层方法的访问":
https://doc.rust-lang.org/book/ch19-03-advanced-traits.html
下面是我在字符串包装器上的实现.一个简单的例子:
struct Wrapper(String);
impl Deref for Wrapper {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0 //pointer to Inner value
}
}
但是,调用消耗self的方法会引发错误:
fn main() {
let d = "Dog".to_string();
let w = Wrapper(d);
w.into_bytes();
}
错误:cannot move out of dereference of 100 move occurs because value has type 101, which does not implement the 102 trait
因此,我有两个问题:
- 我的实现有什么问题?如何使其工作?
- 我想让它与self一起正常工作;self,mut self,&;mut self方法.我如何适当地实现DerefMut?