The Rust Reference
中有一些关于
参考模式的介绍,它说
引用模式取消引用正在匹配的指针 因此,借用它们
所以我尝试写一些代码来感受一下:
struct Myss<'a> {
inner: &'a str,
}
impl<'a> Myss<'a> {
fn new(s: &'a str) -> Self {
Myss { inner: s }
}
}
impl<'a> Deref for Myss<'a> {
type Target = &'a str;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
fn main() {
let s = "abcde";
let mss = Myss::new("abcde");
match &mss { // why not same as & (*(&mss)) -> &(* mss.deref()) -> & (&str) -> &&str
&"abcde" => { // => Errors here: expected `Myss<'_>`, found `&str`
println!("matched");
}
_ => {
println!("others");
}
}
}
ms 变量拥有一个类型
&Myss
,它是对已实现 Deref
特征的类型的引用,并且模式 &"abcde"
imo 是一个参考模式。我预计该值将遵循类似的路径
`& (*(&mss)) -> &(* mss.deref()) -> & (* &Target) -> & 目标 -> & (&str) 因为引用说指针将首先被取消引用,然后被借用(或者我错过了什么?)
可以与类型 & (&str) 的模式 &"abcde" 进行匹配。
但是编译器抱怨
Mismatched types
expected `Myss<'_>`, found `&str`
为什么引用不是像引入引用一样先解引用然后借用?
(编译器版本: rustc 1.77.2)
我不知道参考文献中的“因此,借用它们”是什么意思,参考模式不借用任何东西,它们只是取消引用。
但是,他们不会调用
Deref
,这就是你的代码不起作用的原因。模式中的 Deref
是正在进行中的 deref 模式 的主题,尚未完全实现,尚未单独稳定。