[Solved] Help - I am stil learning

So this is my first post. I searched the forum if my question was already answered but I didn't find anything. So basically I want to solve a exercise form Chapter 10.2 of Traits: Defining Shared Behavior - The Rust Programming Language were I should chance the largest function in that way that it returns a reference to avoid heap allocation. So clearly I run into a lifetime issue, because the return value is defined locally in the scope of the largest function. I tried to handle it with static and 'a but it wouldn't work.

The source code, which you find at the nearly end of the link above is as follows:

fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
    let mut largest = list[0];

    for &item in list.iter() {
        if item > largest {
            largest = item;
        }
    }

    largest
}

fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let result = largest(&number_list);
    println!("The largest number is {}", result);
    
}

Thanks for your help.

Is there a solution collection for the exercises in this "book" anywhere?

Hi!

BTW, you can make your code on the forum more readable like this:

```rust
code here
```

&'static is for things that live forever and are never freed, which is basically limited to only string literals. It's almost never used in normal code.

Your largest function is defined to work only on Copy types, and for these types copying of them is likely to be as fast, or even faster, than returning a reference to them (e.g. on 64-bit platforms returning reference to i32 is twice as much copying as returning i32 by copy).

But returning a borrow is still possible, it only needs moving & around:

2 Likes

Thank you very much, it was way easier than I thought…

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.