为什么需要`&` 在迭代期间解构元组列表? [英] Why is `&` needed to destructure a list of tuples during iteration?

查看:38
本文介绍了为什么需要`&` 在迭代期间解构元组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在迭代元组列表时,需要 & 使其工作.因此这将起作用......

When iterating a list of tuples, the & is needed to make it work. Thus this will work ...

for &(a, b, c) in [("hello", 1.0, 5), ("world", 2.0, 2)].iter() {
    println!("{} {} {}", a, b, c);
}

但这不会......

for (a, b, c) in [("hello", 1.0, 5), ("world", 2.0, 2)].iter() {
    println!("{} {} {}", a, b, c);
}

// type mismatch resolving `<core::slice::Iter<'_, (&str, _, _)> as core::iter::Iterator>::Item == (_, _, _)`:
// expected &-ptr,
found tuple [E0271]

我确信这与我尚未完全内化的解构语法的复杂性有关.

I am sure it has to do with intricacies of the destructuring syntax that I have not yet fully internalised.

你能解释一下 & 符号背后的句法真相吗?

推荐答案

这是因为 iter 数组方法 [T] 返回一个 迭代器,产生 &T.这就是为什么编译器会说expected &-ptr, found tuple [E0271]".

It's because the iter method for an array [T] returns an iterator that yields &T values. That's why the compiler says "expected &-ptr, found tuple [E0271]".

那是为什么?好吧,一般来说,你不能复制T.除非代码假定 T: CopyT: Clone 的限制更严格,否则它只能移动 T<类型的值/代码>.

So why's that? Well, in general, you can't copy T. Unless the code assumes a more restrictive bound of T: Copy or T: Clone, it can only move values of type T.

这是数组的问题,因为无法将单个元素移出数组;这样做会使整个事情无效.

This is a problem for arrays because there's no way to move a single element out of an array; doing so would invalidate the whole thing.

旁白:Vec 和 co.通过在 unsafe 块中实现额外的逻辑来解决这个问题.容器还可以提供 into_iter,它为您提供了一个迭代器,可以增量地消耗容器,允许您将值移出.

Aside: Vec and co. get around this by implementing additional logic in unsafe blocks to make it work. Containers may also provide into_iter which gives you an iterator that incrementally consumes the container, allowing you to move values out.

因为您希望数组 iter 方法适用于 所有 数组,所以它依次产生对每个元素的不可变引用.

Because you want the array iter method to work for all arrays, it instead yields immutable references to each element in turn.

因此,您试图解构 &(&str, f32, i32),而不是 (&str, f32, i32),因此额外的 &.Rust 不喜欢隐式,所以你必须显式解构引用.这也有助于清楚地表明这里发生了一个取消引用和一个副本.

As a result, you're trying to destructure a &(&str, f32, i32), not a (&str, f32, i32), hence the additional &. Rust doesn't like implicitness, so you have to explicitly destructure the reference. This also helps make it clear that there's a dereference and a copy happening here.

这篇关于为什么需要`&amp;` 在迭代期间解构元组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆