Rust中match匹配引用与解引用为何输出结果一致?求解释
为什么Rust中匹配引用和解引用后打印结果相同?
你的代码里两次打印结果一致,核心原因是Rust的Display trait对引用类型的自动解引用行为,而非模式匹配出了问题,具体拆解如下:
第一个
match reference分支里,val的类型确实是&i32(和reference的类型完全一致)。但当你用println!("{}", val)输出时,std::fmt::Displaytrait针对&T类型的实现会自动解引用到内部的T,直接调用T的Display方法。也就是说,打印&4的时候,Rust会自动取出里面的4来显示,不会输出&4这种引用格式。第二个
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
相关产品推荐
相关产品推荐

