Vec<T>会自动转换为[T]吗?

问题描述 投票:0回答:1

考虑这段代码:

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()
有什么区别?

rust vector slice
1个回答
2
投票

这叫

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)

您可以在这里阅读更多内容

https://web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/book/first-edition/deref-coercions.html

https://doc.rust-lang.org/std/ops/trait.Deref.html

© www.soinside.com 2019 - 2024. All rights reserved.