How to get a value from itself or it's reference?

I want to create a function like this:

fn my_sum<T>(arr: T) -> i32
 where T: IntoIterator, T::Item: IntoIterator<Item = i32>
{
    let mut sum = 0;
    for row in arr {
        for item in row {
            sum += item;
        }
    }
    sum
}

It can be called like this

    my_sum([[1, 2, 3]]);
    my_sum(&[[1,2, 3]]);
    my_sum(vec![[1,2, 3]]);

How do I do?

I would probably do this:

fn my_sum<T, I>(arr: T) -> i32
where
    T: IntoIterator,
    T::Item: IntoIterator<Item = I>,
    i32: core::ops::AddAssign<I>,
{
    let mut sum = 0;
    for row in arr {
        for item in row {
            sum += item;
        }
    }
    sum
}

You could also only allow taking references, which is fine for the arrays and vecs you're using, but wouldn't work for something like a channel.

fn my_sum<'a, T>(arr: &'a T) -> i32
where
    &'a T: IntoIterator,
    <&'a T as IntoIterator>::Item: IntoIterator<Item = &'a i32>,
{
    let mut sum = 0;
    for row in arr {
        for item in row {
            sum += item;
        }
    }
    sum
}

And if you only want to take slice-like types, you can use AsRef<[_]>.

fn my_sum<T, U>(arr: T) -> i32
where
    T: AsRef<[U]>,
    U: AsRef<[i32]>,
{
    let mut sum = 0;
    for row in arr.as_ref() {
        for item in row.as_ref() {
            sum += item;
        }
    }
    sum
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.