How do you get an index in a vector?

I'm new to Rust and I keep getting errors relating to vectors, when I try running

use std::io;
use std::ops::Index;

fn main() {

    let mut mem = vec![0];
    let allocated: u16 = 255;
    for i in 0..=allocated  {
        mem.push(0);
    }
    let mut inp = String::new();

    println!(":)");
    io::stdin()
        .read_line(&mut inp)
        .expect("cannot read");

    let tape = inp.split("").collect::<Vec<_>>();
    for iu16 in 0..=tape.len() {
        tape[i] // issue
    }
}

it returns

error[E0425]: cannot find value `i` in this scope
  --> src\main.rs:22:14
   |
22 |         tape[i]
   |              ^ not found in this scope

warning: unused import: `std::ops::Index`
 --> src\main.rs:4:5
  |
4 | use std::ops::Index;
  |     ^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

For more information about this error, try `rustc --explain E0425`.
warning: `bf` (bin "bf") generated 1 warning
error: could not compile `bf` (bin "bf") due to 1 previous error; 1 warning emitted

how do I fix this?

    for iu16 in 0..=tape.len() {
    //   ^^^

Numeric type suffixes like u16 and f32 are only valid on literals like 123 or 4.5, not on variable declarations. (There is no way to annotate the type in that position so far.) So your variable is called "iu16" not "i". Just leave off the u16 suffix.


    for i in 0..=tape.len() {
    //        ^^^^^^^^^^^^^

This ..= range includes the last number (tape.len()), and indexing by tape.len() will panic. You need indices less than tape.len(), which you can get by using a non-inclusive range:

    for i in 0..tape.len() {
    //        ^^

Instead of indexing, you can use iteration in a number of ways.

    for &s in &tape {
        // s is like tape[i]
        let _s: &str = s;
    }
    
    for s in tape.iter().copied() {
        // s is like tape[i]
        let _s: &str = s;
    }

    // This version consumes `tape` so you can't use it afterwards    
    for s in tape {
        // s is like tape[i]
        let _s: &str = s;
    }
    
    // You could just not collect the split too
    for s in inp.split("") {
        let _s: &str = s;
    }
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.