Hello there. I'm pretty new to Rust so I'm struggling even with the most basic things.
I'm building a simple method (gen_these_many_primes) that returns a vector containing the first n primes.
For example, the call: gen_these_many_primes(4) should return the vector vec![2, 3, 5, 7]
This is my implementation:
pub fn gen_these_many_primes(n: u32) -> Vec<u32> {
let mut primes_vec = vec![];
let mut current_prime = 2;
let mut current_iter: u64 = 0;
const MAX_ITER: u64 = 10000;
while current_prime <= n {
if is_prime(current_prime) {
primes_vec.push(current_prime);
current_prime += 1;
}
// Avoid infinite loop
current_iter += 1;
if current_iter >= MAX_ITER {
break;
}
}
primes_vec
}
(Note 1: This method makes use of another is_prime method I've already implemented, which works well. You input a number and returns true if prime and false otherwise. I can post this method if necessary, I just didn't want to make the post unnecessarily long).
(Note 2: I am aware this is not an optimal algorithm, but for now I'm more interested in learning Rust than in optimization.)
So, I'm calling gen_these_many_primes from within another function called nth, which returns the nth-prime in the generated list:
pub fn nth(n: u32) -> u32 {
let primes = gen_these_many_primes(n);
return primes[n];
}
For example, the call nth(3) should return 7. nth(0) should return 2.
However, when I call this method, I obtain the following error:
error[E0277]: the type
[u32]
cannot be indexed byu32
I've run the command rustc --explain E0277 as suggested, and it mentions something about traits, but I don't understand the error very well.
Maybe someone can point me in the right direction.
Forever grateful.
Jose.