You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何该Rust引用模式未先解引用再借用后匹配?

关于Rust引用模式与Deref trait的匹配问题

Rust参考手册中对引用模式的说明如下:

引用模式会对被匹配的指针进行解引用,进而借用它们

为验证这一特性,我编写了如下测试代码:

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 { // 我原以为这里等价于 & (*(&mss)) -> &(* mss.deref()) -> & (&str) -> &&str
        &"abcde" => { // 此处报错:expected `Myss<'_>`, found `&str`
            println!("matched");
        }
        _ => {
            println!("others");
        }
    }
}

变量&mss是实现了Deref trait的自定义类型的引用,我原本认为模式&"abcde"作为引用模式,会按& (*(&mss)) -> &(* mss.deref()) -> & (&str) -> &&str的路径处理,从而能和类型为&(&str)的&"abcde"模式匹配。但编译器报出如下错误:

Mismatched types
expected `Myss<'_>`, found `&str`

问题原因

核心误区在于:引用模式的自动解引用仅针对原生引用类型(&T/&mut T),不会触发自定义类型的Deref trait。

具体来说:

  • 你匹配的&mss类型是&Myss<'_>,模式&"abcde"期望匹配的是&(&str)。但Rust的模式匹配逻辑中,不会为实现了Deref的自定义类型自动递归解引用——引用模式的“解引用”逻辑只适用于原生指针,而非自定义的Deref实现。

解决方法

有几种方式可以让代码正确匹配:

  1. 手动触发Deref解引用
    在匹配前手动解引用自定义类型,得到原生引用后再匹配:
match &*mss { // &*mss 触发Deref得到 &&str
    &"abcde" => {
        println!("matched");
    }
    _ => {
        println!("others");
    }
}
  1. 直接匹配结构体内部字段
    跳过Deref,直接匹配Myss的inner字段:
match &mss {
    Myss { inner: &"abcde" } => {
        println!("matched");
    }
    _ => {
        println!("others");
    }
}
  1. 利用表达式中的自动Deref
    在match的表达式中直接使用*mss,触发Deref得到&str,然后直接匹配字符串字面量:
match *mss { // *mss 触发Deref得到 &str
    "abcde" => {
        println!("matched");
    }
    _ => {
        println!("others");
    }
}

内容的提问来源于stack exchange,提问作者hliu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 00:05:54