我实现了结构Deref的特征,它允许我通过orMyString使用类型的对象。MyString*oo.deref()
但是,当我实现该Drop特征MyString时,已经实现的Deref特征就不能在该特征内部使用Drop。为什么?
use std::ops::Deref;
use std::ops::DerefMut;
struct MyString {
s: String,
}
impl Deref for MyString {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.s
}
}
impl DerefMut for MyString {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.s
}
}
impl Drop for MyString {
fn drop(&mut self) {
// println!("string dropped: {}", *self); // `MyString` doesn't implement `std::fmt::Display`
// …Run Code Online (Sandbox Code Playgroud) let mut a = Box::new("123".to_string());
let b = Box::new( &mut a);
b.push('4');
assert_eq!( "1234", b.as_str());
// lets see the types:
// let x001: Box<&mut Box<String>> = b;
// let x001:&mut Box<String> = *b;
// let x001:Box<String> = **b;
// let x001:String = ***b;
// let x001:str = ****b;
let c = Box::new("456".to_string());
**b = c;
b.push('9');
(*b).push('9');
(**b).push('9');
(***b).push('9');
// (****b).push('9'); // no method named `push` found for type `str` in the current scope
// c.push( 'a'); // cannot mutate …Run Code Online (Sandbox Code Playgroud)