I am trying to pass an immutable reference to a Vec
(a slice) to a function which will fill the Vec
with incrementing values, and then iterate over them again replacing some of those values with zeroes.
My thinking is that the vector is immutable (the data types and size of the vector will never change) but the contents of the vector should be mutable references to integers. Or should they be the actual values of the integers themselves (and not references)?
This have proven a difficult task.. I've read about mutability and borrowing, and I feel I have an OK understanding of this. I also have a cursory understanding of how referencing, dereferencing, pointers, etc. work in C, but I think I am struggling with the syntax of Rust to achieve this.
Am I thinking about this the wrong way? In Rust, is it more idiomatic to create a copy of a potentially huge Vec
, operate on that, and return it?
This is my code so far (does not compile, many errors):
#![feature(iterator_step_by)]
pub fn nth(n: usize) {
let size: usize = (2 as f64 * n as f64 * (n as f64).ln()) as usize;
// Set an upper bound for seiving.
let size_sqrt: usize = (size as f64).sqrt().ceil() as usize;
let nums: Vec<&mut usize> = Vec::with_capacity(size);
sieve(nums, &size, &size_sqrt);
}
fn sieve(nums: [&mut usize], size: &usize, size_sqrt: &usize) {
for i in 0..*size {
nums[i] = i;
}
for num in nums {
if num < 2 {
continue;
} else if num > *size_sqrt {
break;
}
for x in (num.pow(2)..size).step_by(*num) {
nums[x] = 0;
}
}
}
let mut v = vec![1, 2, 3]; v[0] = 42;
(Yes, I know it seems like I'm being obtuse, but I'm trying to see if I can figure out the real underlying question here). – Shepmaster