Quick little Codewars problem I'm trying to solve



So in theory, sum_of_n will produce a Vec where each item is the gaussian sum up to that point. I’m starting from 1 just for clarity.

[gauss(1), gauss(2), gauss(3), gauss(4)] etc
[1, 3, 6, 10] etc

It seems like res is never getting those values pushed, because I don’t see anything printing…?

I’m not a rust expert, so maybe I am glossing over an important detail here.


There is something printed:


Rust functions have to declare their return type. If nothing is specified, a function returns the empty tuple, also known as the unit type: (). Re-read the chapter on functions to refresh your knowledge.

fn sum_of_n(n: i32) -> Vec<i32> {
    // -> Vec<i32> // should be [gauss(1), gauss(2), gauss(3) etc]
    let mut res = Vec::new();
    for i in 1..6 {

I’d write this with more iterators, however:

fn sum_of_n(n: i32) -> Vec<i32> {

The recursive implementation seems inefficient, however, so a rewrite might look like:

fn sum_of_n(n: i32) -> Vec<i32> {
    let mut sum = 0;
    (1..6).map(|i| {
        sum += i;


Ah, I see. Wonderful, thank you so much.

I will reread that chapter right now.


Aaand this?

fn sum_of_n(n: i32) -> Vec<i32> {
    (1..6).scan(0, |sum, i| { *sum += i; *sum }).collect()


Yes! Great!

I ended up doing something similar with map.

Afk now, will update this post later with code for posterity.