I'm searching an easy, not bloated solution for an easy problem.
Code (playpen):
use std::ops::Range;
// Sum of square numbers from 1 to 10 # 1^2 + 2^2 + 3^2 ...
fn sum_square(v: &[i64; 10]) -> i64 {
let mut sum: i64 = 0;
for x in v {
sum += x * x;
}
return sum;
}
// Square sum of the added numbers from 1 to 10 # (1+2+3+...)^2
fn square_sum(v: &[i64; 10]) -> i64{
let mut sum: i64 = 0;
for x in v {
sum += x;
}
return sum*sum;
}
fn main() {
let v: [i64; 10] = [1,2,3,4,5,6,7,8,9,10];
let diff = sum_square(&v) - square_sum(&v);
println!("{}", diff);
}
I have an array in the main function, filled with numbers from 1-10 (yes I know [1..11] doesn't work, but what's the best solution? Using "range" is out of question, I want an array without having to type each number). Now I need to iterate over this array multiple times (here 2x) in different functions.
I don't want to use .copy() (because I don't want to move), I want to borrow the array to the functions like explained here: https://i.stack.imgur.com/VlZ8N.jpg
fn main() {
let v: [i64; 10] = [1..11];
let diff = sum_square(&v) - square_sum(&v);
println!("{}", diff);
}
Two functions, each iterating over this array. So I just use a
fn sum_square(v: &[i64; 10]) -> i64 {
let mut sum: i64 = 0;
for x in v {
sum += x * x;
}
return sum;
}
Seems to work. If I use the second function
// Square sum of the added numbers from 1 to 10 # (1+2+3+...)^2
fn square_sum(v: &[i64; 10]) -> i64{
let mut sum: i64 = 0;
for x in v {
sum += x;
}
return sum*sum;
}
I get an error: type mismatch resolving <core::slice::Iter<'_, i64> as core::iter::Iterator>::Item == i64
: