这里是否发生了引用模式?


fn main() {
// i passed a reference to a value of type i32
print_type_of(&1); // but print: i32
// but if i pass a double reference
print_type_of(&&1); // it print &i32, not &&i32
// i passed a referece to a value of type i32
print_type_of_without_ampersand(&1); // now print: &i32 as expected
referece_pattern(&1); // it works!
// -> update <-
// if i have
let x = 1;
let ref_x = &&x;
// this is the implementation of Deref for &T
// #[stable(feature = "rust1", since = "1.0.0")]
// #[rustc_const_unstable(feature = "const_deref", issue = "88955")]
// impl<T: ?Sized> const Deref for &T { //! -> here T should be &&i32 or &i32 ? <- !
//     type Target = T;
//     #[rustc_diagnostic_item = "noop_method_deref"]
//     fn deref(&self) -> &T { // if here self is &&i32, and T should be &&i32 too
//         *self // <- here  after deference self should be &i32, but &T is still &&i32 that is incompatible <- !
//     }
// }
// -> end update <-
}
// amperand is before the type name
// so it should not be a reference pattern
fn print_type_of<T>(_: &T) {
println!("{}", std::any::type_name::<T>())
}
fn print_type_of_without_ampersand<T>(_: T) {
println!("{}", std::any::type_name::<T>())
}
// reference pattern happens here
// amperand is before the parameter name
fn referece_pattern(&x: &i32) {
assert!(x == 1);
println!("it works!");
}

我也读了一篇关于参考模式的文章,但是它没有解释这个。

更新:我在代码中添加了新的内容,关于&T

的Deref实现

不太确定哪里混淆了。

fn print_type_of<T>(_: &T);

是一个具有类型参数T的函数,它接收对T(&T)的引用。所以如果你给它一个&i32,引用"指向"的类型是i32,所以当你以后调用type_name::<T>()你得到i32因为这就是T

如果T像你期望的那样解析为&i32,那么它将期望一个类型为&&i32的项目。

没有引用模式,只是在进行替换后检查类型的方式。

最新更新