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

Rust中match匹配引用与解引用为何输出结果一致?求解释

为什么Rust中匹配引用和解引用后打印结果相同?

你的代码里两次打印结果一致,核心原因是Rust的Display trait对引用类型的自动解引用行为,而非模式匹配出了问题,具体拆解如下:

  1. 第一个match reference分支里,val的类型确实是&i32(和reference的类型完全一致)。但当你用println!("{}", val)输出时,std::fmt::Display trait针对&T类型的实现会自动解引用到内部的T,直接调用T的Display方法。也就是说,打印&4的时候,Rust会自动取出里面的4来显示,不会输出&4这种引用格式。

  2. 第二个match *reference分支里,*reference直接解引用成了i32类型,val就是4本身,打印结果自然是4。

如果想验证第一个val确实是引用类型,可以换用Debug格式打印,或者输出内存地址:

fn main() {
    let reference = &4;

    match reference {
        val => {
            // 用Debug格式打印引用本身
            println!("Got a reference via destructuring: {:?}", val);
            // 打印引用的内存地址
            println!("Address of the reference: {:p}", val);
        }
    }
    match *reference {
        val => println!("Got a value via destructuring: {}", val),
    }
}

这段代码的输出会类似:

Got a reference via destructuring: &4
Address of the reference: 0x7ffdxxxxxxxxx
Got a value via destructuring: 4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 11:57:19