考虑这段代码:
fn funA() {
let v1: Vec<i32> = vec![1, 2, 3];
funB(&v1); // question_A
v1.iter(); // question_B
}
fn funB(slice: &[i32]) {
// slice type is &[i32] by sure
}
我很困惑,因为
funB
需要类型 &[i32]
,而调用者使用类型 &Vec<i32>
。这是调用堆栈的一部分,我可以看到有一些 deref
和 as_ptr
操作,但不确定它是如何工作的。
core::ptr::mut_ptr::<impl *mut T>::is_null (@core::ptr::mut_ptr::<impl *mut T>::is_null:42)
alloc::vec::Vec<T,A>::as_ptr (@<alloc::vec::Vec<T,A> as core::ops::deref::Deref>::deref:19)
<alloc::vec::Vec<T,A> as core::ops::deref::Deref>::deref (@<alloc::vec::Vec<T,A> as core::ops::deref::Deref>::deref:11)
hello_cargo::funA (/Users/path-to-hello_cargo/src/main.rs:15)
...
main (@main:12)
start (@start:639)
Vec::as_slice()
有什么区别?
这叫
Deref
强制
/// Vec<T> implements Deref as follows
impl Deref for Vec<T> {
type Target = &[T];
fn deref(&self) -> &Self::Target;
}
// meaning you can call
let vector: Vec<T> = ...
let slice: &[T] = vector.deref();
// Rust can call .deref() automatically whenever needed (coercion)
您可以在这里阅读更多内容