How to iterate over an array of integers?

Vega

What can I do to iterate over an array of integers in Rust?

fn main () {

    let mut array: Vec<i64> = vec![2];

    for k in range(3, 13195) {
        for p in array.iter() {
           if (k % p != 0) {array.push(p)};
        }        
    }
}

Gives me the compiler error:

rustc "Task2_minimalcode.rs" (im Verzeichnis: C:\Users\XXX\Documents\Rust - Project Euler)

Task2_minimalcode.rs:7:14: 7:15 error: mismatched types: expected _, found &i64 (expected integral variable, found &-ptr) [E0308] Task2_minimalcode.rs:7 if (k % p != 0) {array.push(p)};
^ Task2_minimalcode.rs:7:34: 7:35 error: mismatched types: expected i64, found &i64 (expected i64, found &-ptr) [E0308]

Task2_minimalcode.rs:7 if (k % p != 0) {array.push(p)}; ^ error: aborting due to 2 previous errors Failed compilation.

DK.

Quoth the error message:

error: mismatched types: expected i64, found &i64 (expected i64, found &-ptr)

Vec<T>::iter gives you an iterator over &T (references to T). If you don't intend to ever use the vec again, you can use for p in array or for p in array.into_iter(). If you do want to use it again, you have several options:

  • &array or array.iter(), and dereference p when using it.
  • array.iter().cloned()
  • array.iter().map(|e| *e) (effectively the same as above)

If all this talk about references doesn't make sense, you should probably read the section of the Rust Book on Pointers.

Remember that you can trick the compiler into telling you the type of a variable like so: let _:() = p; -- the error message will contain the true type.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related