String
实现Deref<Target = str>
,这意味着将编译以下代码:
fn save(who: &str) {
println!("I'll save you, {}!", who);
}
save(&String::from("Madoka"));
如果我创建的自定义类型也实现了Deref<Target = str>
,那么它也可以工作:
struct Madoka;
impl Deref for Madoka {
type Target = str;
fn deref(&self) -> &Self::Target {
"Madoka"
}
}
save(&Madoka);
现在,让我们尝试强制使用另一种类型,例如u32
。似乎也可以:
fn reset(how: &u32) {
println!("Reset {} times", how);
}
struct Homura;
impl Deref for Homura {
type Target = u32;
fn deref(&self) -> &Self::Target {
&42
}
}
reset(&Homura);
但是当我将表达式包装在一个块中时,它不再编译:
reset(&{ Homura });
error[E0308]: mismatched types
--> src/main.rs:17:14
|
17 | reset(&{ Homura });
| ^^^^^^ expected u32, found struct `main::Homura`
|
= note: expected type `u32`
found type `main::Homura`
奇怪的是,与&str
等效的表达式可以很好地编译:
save(&{ Madoka }); // OK
为什么第一个表达式无法编译,但是第二个成功?