Here is modified version of example of usage Deref:
use std::ops::Deref;
use std::rc::Rc;
#[derive(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
pub struct InternedString {
string: Rc<String>,
}
impl InternedString {
#[inline]
pub fn new(string: &'static str) -> InternedString {
InternedString {
string: Rc::new(string.to_owned()),
}
}
}
impl Deref for InternedString {
type Target = str;
fn deref(&self) -> &str { &self.string }
}
struct DerefExample<T> {
value: T
}
impl<T> Deref for DerefExample<T> {
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}
fn main() {
let x = DerefExample { value: 'a' };
assert_eq!('a', *x);
match *x {
'a' => (),
_ => (),
};
let s = InternedString::new("aaa");
match *s {
"test" => (),
_ => (),
};
}
it is not compiled, with error:
55 | "test" => (),
| ^^^^^^ expected str, found reference
|
= note: expected type `str`
= note: found type `&'static str`
but if I call deref
method by hands:
match s.deref() {
"test" => (),
_ => (),
}
all compiled without errors, what is difference between *s
and s.deref()
, and why for char
all works fine?