gpt4 book ai didi

rust - 为什么这里的 for 循环中必须使用可变引用?

转载 作者:行者123 更新时间:2023-12-03 11:26:04 25 4
gpt4 key购买 nike

这可能是一个愚蠢的问题,但这有点让我抓狂。我有这个简单的代码:

let args = env::args();
println!("num args read: {}", args.len());

for element in args {
println!("{}", element);
}

let arg_string: String = args.collect();

这不起作用并给出错误:

    |
4 | let args = env::args();
| -------- move occurs because `args` has type `std::env::Args`, which does not implement the `Copy` trait
...
8 | for element in args {
| ----
| |
| `args` moved due to this implicit call to `.into_iter()`
| help: consider borrowing to avoid moving into the for loop: `&args`
...
14 | let arg_string: String = args.collect();
| ^^^^ value used here after move

这是有道理的,因为 into_iter() 调用消耗了 self。因此,我尝试将 for 循环修改为 for element in &args,但出现此错误:

9 |     for element in &args {
| -^^^^
| |
| `&std::env::Args` is not an iterator
| help: consider removing the leading `&`-reference
|
= help: the trait `std::iter::Iterator` is not implemented for `&std::env::Args`
= note: `std::iter::Iterator` is implemented for `&mut std::env::Args`, but not for `&std::env::Args`
= note: required by `std::iter::IntoIterator::into_iter`

为什么我不能通过迭代器迭代引用?我发现我可以做到

let mut args = env::args();
println!("num args read: {}", args.len());

for element in &mut args {
println!("{}", element);
}

let arg_string: String = args.collect();

这消除了编译器错误。为什么我必须在此处采用可变引用而不只是引用?

最佳答案

您正在使用 Args 就像它是一个集合,但它不是;它是一个迭代器。您的 &mut 解决方法可以满足编译器的要求,但实际上并没有按照您的意愿进行。 for 循环将耗尽 迭代器,这意味着 args.collect() 不会产生任何值。

修复方法是为每次使用分别调用 env::args()你并没有通过尝试使用相同的变量来保存任何东西。我忘记了 Args 创建拥有的 String,所以你可能会更好如果需要多次迭代,请先将参数收集到 Vec 中。

关于rust - 为什么这里的 for 循环中必须使用可变引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64312031/

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