gpt4 book ai didi

rust - 在 rust 数组和 vec 上使用 `for` 循环

转载 作者:行者123 更新时间:2023-12-05 03:17:19 25 4
gpt4 key购买 nike

在 Rust 数组上使用 for 循环可以正常工作:

fn main() {
let v = [1, 2, 3, 4, 5];
for _ in v.into_iter() {}
for _ in v.into_iter() {}
}

但是替换为 vec 不会编译:

fn main() {
let v = vec![1, 2, 3, 4, 5];
for _ in v.into_iter() {}
for _ in v.into_iter() {}
}

错误:

use of moved value: `v`

我明白为什么这个程序不能与 vec 一起工作。但为什么它适用于数组?我原以为数组示例中会出现类似的错误,但它没有给出任何错误。

最佳答案

正如另一位评论者所提到的,Rust 中的数组实现了 Copy 特性,因此可以多次按值传递,而 Vector 类型必须显式 clone()d 实现相同的行为。

在 Rust 中,当函数的参数是按值传递时,编译器默认对除最后一次调用之外的所有调用执行副本移动,在最后一次调用时它将转移原始所有权,而不是复制/克隆。如果未实现 Copy,编译器将不会自动运行 clone()

这是Copy 特征的文档:https://doc.rust-lang.org/std/marker/trait.Copy.html

Array 的 Copy 文档可以在这里找到:https://doc.rust-lang.org/std/primitive.array.html#impl-Copy-for-%5BT%3B%20N%5D

这是一篇包含更多详细信息的精彩文章:https://colinsblog.net/2021-04-16-rust-ownership-comparisons/

关于rust - 在 rust 数组和 vec 上使用 `for` 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74168758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com