Error: the trait `core::ops::Index<i32>` not implemented for type `[i32]`


#1
use std::io;
fn main(){

    let mut stk: [i32; 5];
    let top: i32 = -1;
    println!("Im in main");

    push(top,&mut stk);
    pop(12);
    println!("Stack is {}",isEmpty(top));

}

fn push(top: i32,stk: &mut [i32]) -> i32{
    let temp: i32;
    if isEmpty(top) == -1 || isEmpty(top) == 1{
        1
    }else {
        println!("Enter Element To Push : ");
        top +=1;
        println!("{:?}",readInt() );
        stk[top] = 1;
             1
    }
}

fn pop(y: i32) -> i32{
 println!("Implemeting : Later");
 0
}

fn isEmpty(top: i32) -> i32{
    if top == -1{
    println!("Stack is Empty");
    0
}else{
        println!("Stack Is Full");
        1
        }
}
fn readInt() -> i32{
    let mut guess = String::new();

                        io::stdin().read_line(&mut guess)
                                   .ok()
                                   .expect("failed to read line");

     let guess: i32 = guess.trim().parse()
                                  .ok()
                                  .expect("Please type a number!");

            return guess;
}


#2

stk[top as usize] ?


#3

soos is correct, to index an array, slice or a vector, you need usize indices


#4

Thank you ! This works, but please could you explain it in detail via example.


#5

Your variable top is an index into the stack, right? In that case it should be usize, not i32.

You’re also using -1 as a sentinel value. In Rust you could experiment with using Option instead. Top could be an Option<usize> where None means there is nothing in the stack, and Some(_) holds a valid top.

I see that you’re returning i32 from isEmpty, you should use the type bool! It’s easier to read & understand the code that way.


#6

Also, it’s not as critical, as what @bluss pointed out, but Rust convention for methods and functions naming is snake_case, and compiler should warn you about it.