Joseph Stevens
Joseph Stevens

Reputation: 23

Compilation error whilst reading item in vector in rust rustc(E2077)

I am attempting to generate the nth term of the fibonacci sequence in order to practice using rust, below is the function that I wrote to try and acheive this:

fn findTerm(term: i128) -> i128 {
    let mut fibonacci: Vec<i128> = Vec::new();
    fibonacci.push(1);
    fibonacci.push(1);

    while fibonacci.len() < term.try_into().unwrap() {
        fibonacci.push(fibonacci[fibonacci.len() - 1] + fibonacci[fibonacci.len() - 2]);
    }

    println!("{:?}", fibonacci);

    fibonacci[term - 1]
}
error[E0277]: the type `[i128]` cannot be indexed by `i128`
  --> src/lib.rs:12:5
   |
12 |     fibonacci[term - 1]
   |     ^^^^^^^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `SliceIndex<[i128]>` is not implemented for `i128`
   = help: the trait `SliceIndex<[T]>` is implemented for `usize`
   = note: required because of the requirements on the impl of `Index<i128>` for `Vec<i128>`

Upvotes: 0

Views: 78

Answers (1)

jthulhu
jthulhu

Reputation: 8657

Vectors can only be indexed by integers of type usize, that's the size of a pointer (and indexing a vector is roughly equivalent to doing pointer arithmetic). Therefore you need to do:

fn find_term(term: i128) -> i128 {
    let mut fibonacci = Vec::new();
    fibonacci.push(1);
    fibonacci.push(1);

    while fibonacci.len() < term.try_into().unwrap() {
        fibonacci.push(fibonacci[fibonacci.len() - 1] + fibonacci[fibonacci.len() - 2]);
    }

    println!("{:?}", fibonacci);

    fibonacci[(term - 1) as usize]
}

See the playground.

Upvotes: 1

Related Questions