问题描述
我似乎不明白为什么:
let a = Box::new(5i32);
let _:() = *a;
告诉我第二行分配的类型是 i32
而不是 &i32
因为 Deref.deref()
(我假设在 *a
) 处被调用,返回 &T
.
tells me that the assigned type on the second line is i32
and not &i32
since Deref.deref()
(which I assume is being called at *a
), returns &T
.
另外,如果我自己调用 deref()
:
Also, if I were to call deref()
myself:
let _:() = <Box<i32> as Deref>::deref(&a);
我得到了预期的 &i32
.
推荐答案
*foo
与调用 foo.deref()
不同.如果是这样,您将永远无法实际取消引用一个值.^_^
*foo
is not the same as calling foo.deref()
. If it were, you'd never be able to actually dereference a value. ^_^
*
是调用 Deref::deref
然后进入提供的地址"的语法糖.这正是人们对该运营商的期望.Deref
的存在是为了使其可扩展.
*
is syntactic sugar for "call Deref::deref
and then go into the address provided". This is just what people expect from that operator. Deref
exists to make it extensible.
最后一点掩盖了一些细节,bluss 的回答涵盖的更好.
That last bit glosses over some details that bluss' answer covers much better.
另见:
这篇关于取消引用 Box<T>返回值而不是参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!