vendredi 23 août 2019

A vector is created inside an if block in Rust. How to use it after the the scope of if ends?

I am learning Rust. I am trying to calculate list of prime numbers upto some number. For that I need to create a vector(vec1) inside if block and use it outside the scope of if.

I tried a code with same logic in matlab and it works.

A simplified version of the actual code looks like this-

fn main() {
let mut initiate=1;
let mut whilechecker=2;

while whilechecker>0{
whilechecker=whilechecker-1;

if initiate==1{ 
let mut vec1=vec![2];
}

  for i in  &vec1{
    if *i==2{
        break   
         }
  }//for

initiate=2;
vec1.push(5);
}//while

}//main

It is suppoesed to give a list of prime numbers(vec1). But since it is simplified code it should compile and giving a vector (vec1) will suffice. But compiler says: cannot find value vec1 in this scope at for i in &vec1{ and at vec1.push(5);. Can you make it compile?

Aucun commentaire:

Enregistrer un commentaire