Expected & -ptr, tuple found, iterating over the tuple array

I have an array:

const adjacent: [(i8, i8); 8] = 
    [(-1, -1), (-1, 0), (-1, 1), (-1, 0), (1, 0), (1, 1), (1, 0), (1, -1)];

This array represents all neighboring cell neighbors in the ROWxCOLUMN grid. To iterate over this array to find all the neighbors, I do

for k in adjacent.into_iter() {
    let (i, c) = (k.0, k.1);
    if let Some(a) = grid.get(r+i, j+c) {
        /* ... */
    }
}

The second line seems that it can be replaced by K, but this causes an error if you write for (i, c) in adjacency.into_iter() { ...

error: type mismatch resolving `<core::slice::Iterator>::Item == (_, _)`:
expected &-ptr
found tuple

what's going on here? Can someone explain why I can not do this?

+4
source share
2 answers

Decision

Something is happening there. First working code:

for &(i, c) in &adjacent { }

The following is a more detailed explanation.


Problem

&(i8, i8), . (i, c). , ; . , & , , .

:

<anon>:11:5: 11:42 error: type mismatch resolving `<core::slice::Iter<'_, (i8, i8)> as core::iter::Iterator>::Item == (_, _)`:
 expected &-ptr,
    found tuple [E0271]
<anon>:11     for (i, c) in adjacent.into_iter() {}
              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

, : . , (, core::slice::Iter<'_, (i8, i8)>) , - "" (, <core::iter::Iterator>::Item == (_, _)).

"" (_, _), , , : (i, c). ? , , Iterator type Item = &'a T. 'a , T. , T, : core::slice::Iter<'_, (i8, i8)>. , T - (i8, i8), &(i8, i8).

IntoIterator

.into_iterator() . , : for _ in adjacent

the trait `core::iter::Iterator` is not implemented for the type `[(i8, i8); 8]`

: 8? , , , for.

"", , Iterator , IntoIterator. (, Vec,...) Iterator , IntoIterator. array IntoIterator - . , , IntoIterator:

impl<'a, T> IntoIterator for &'a [T; 8]
    type Item = &'a T

impl<'a, T> IntoIterator for &'a mut [T; 8]
    type Item = &'a mut T

, , . Item. , IntoIterator for [T; 8] ? .

, &adjacent adjacent - . . into_iterator? ... , : . .

TL; DR: adjacent - (array, Vec,...), :

  • for _ in &adjacent: . , !
  • for _ in &mut adjacent: , , .
  • for _ in adjacent: , , . ! .
+7

, , & :

for &(i, c) in adjacent.into_iter() {
    let (i, c) = (k.0, k.1);
    if let Some(a) = grid.get(r+i, j+c) {
        /* ... */
    }
}

for , .

, , :

let mut it = adjacent.into_iter();
loop {
    match it.next() {
        Some((i, c)) => println!("{}, {}", i, c),
        None => break,
    }
}

src/main.rs:7:18: 7:24 error: mismatched types:
 expected `&(i8, i8)`,
    found `(_, _)`
(expected &-ptr,
    found tuple) [E0308]
src/main.rs:7             Some((i, c)) => println!("{}, {}", i, c),
                               ^~~~~~
+4

Source: https://habr.com/ru/post/1616813/


All Articles