Fra*_*dom 1 traits dereference rust drop
我实现了结构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`
// println!("string dropped: {}", self.deref()); // `main::MyString` doesn't implement `std::fmt::Display`
println!("string dropped: {}", self.s); // works
}
}
let s1 = MyString {
s: "abc".to_string(),
};
println!("s1: {}", *s1);
println!("s1: {}", s1.deref());
Run Code Online (Sandbox Code Playgroud)
因为selfin deref 是引用,所以需要解引用两次:
println!("string dropped: {}", **self);
println!("string dropped: {}", self.deref().deref());
Run Code Online (Sandbox Code Playgroud)