数组为什么需要引用,而向函数传递参数时,向量不需要引用?

huangapple go评论61阅读模式
英文:

Why does an array require a reference, but a vector doesn't when we pass them as a parameter to a function?

问题

数组需要引用,而向量不需要引用作为参数传递给函数是因为它们有不同的所有权和借用规则。在Rust中,数组是具有固定大小的数据结构,而且通常是栈分配的。因此,将数组传递给函数时,通常需要使用引用来避免所有权转移。

向量(Vec)是一个动态大小的数据结构,通常在堆上分配内存。在Rust中,向量可以被移动或复制,而不会导致所有权问题。因此,通常不需要将向量作为引用传递给函数,因为它们可以被有效地移动或复制。

这是Rust的所有权和借用系统的一部分,旨在确保内存安全和避免悬挂引用等问题。

英文:
fn _print_array(arr: &[i32])
{
    println!("Array : {:?}", arr);
}

pub fn print_array()
{
    let _a:[i32;3]=[1,2,3];
    _print_array(&_a);
}

fn _print_vector(v: Vec<i32>)
{
    println!("Vector : {:?}", v);
}

pub fn print_vector()
{
    let _v:Vec<i32> = vec![1, 2, 3];
    _print_vector(_v);
}

Why does an array require a reference, but a vector doesn't when we pass them as a parameter to a function?

答案1

得分: 1

[i32] 不是一个 array,它是一个 slice。切片是无大小的,因此无法将它们作为函数参数传递。你可以传递数组。

fn print_actual_array<const LEN: usize>(arr: [i32; LEN]) {
    println!("Array : {:?}", arr);
}

你可以使用指针类型,比如引用 (&)、Box 或原始指针 (*const) 来传递无大小的类型。Vec 包含一个指向切片的 *const 指针。

当你这样做时

let _a: [i32; 3] = [1, 2, 3];
_print_array(&_a);

实际上是将数组强制转换为切片(类似于 Derefas),显式地看起来像这样:

let _a: [i32; 3] = [1, 2, 3];
let _b: &[i32] = &_a;
_print_array(_b);
英文:

[i32] is not an array, it's a slice. Slices are unsized, and therefore you can't pass them as function parameters. You can pass arrays.

fn print_actual_array&lt;const LEN: usize&gt;(arr: [i32; LEN]) {
    println!(&quot;Array : {:?}&quot;, arr);
}

You can pass unsized types using a pointer type, such as references (&amp;), Box, or raw pointers (*const). Vec holds a *const pointer to a slice.

When you do this

let _a: [i32; 3] = [1, 2, 3];
_print_array(&amp;_a);

you're actually coercing the array into a slice (similar to Deref or as) which looks like this explicitly

let _a: [i32; 3] = [1, 2, 3]
let _b: &amp;[i32] = &amp;_a;
_print_array(_b);

huangapple
  • 本文由 发表于 2023年3月7日 04:33:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655571.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定