1

I am new to Rust and was making a simple program to practice which takes 2 numbers and prints the numbers between them. This is my code

fn main() {
    let a: u32 = 2;
    let b: u32 = 10;
    let a = result(&a, &b);
    println!("{:?}", a);
}

fn result(a: &u32, b: &u32) -> [Vec<&u32>] {
    let mut vec = Vec::new();
    for x in a..b {
        vec.push(a);
    }
    vec
}

When i run this program, i get this error

fn result(a: &u32, b: &u32) -> [Vec<&u32>] {
|                                     ^ expected lifetime parameter

The concepts of borrowing and lifetimes are still very new and strange to me. Please help me in determining where i am wrong.

edwardw
  • 12,652
  • 3
  • 40
  • 51
Dino
  • 13
  • 1
  • 3
  • [How to return new data from a function as a reference without borrow checker issues?](https://stackoverflow.com/questions/36213630/how-to-return-new-data-from-a-function-as-a-reference-without-borrow-checker-iss) is another very similar question. – trent Oct 16 '19 at 13:21
  • Even though the question was already answered, I'd like to point out that there's a chapter in the Rust book that is fitting to understand this problem: https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html – elsoja Oct 18 '19 at 21:53

1 Answers1

1

The error message is quite clear here:

this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from a or b

Providing an explicit lifetime would help the compiler understand what you're trying to do:

fn result<'a>(a: &'a u32, b: &'a u32) -> Vec<&'a u32> {
    let mut vec: Vec<&'a u32> = Vec::new();
    for x in *a..*b {
        vec.push(&x);
    }
    vec
}

But the above wouldn't work either, as borrowing x results in borrowing a variable whch only lives in the scope a single iteration:

 vec.push(&x);
           ^^ borrowed value does not live long enough

What you probably want is to avoid borrowing altogether:

fn result(a: u32, b: u32) -> Vec<u32> {
    let mut vec = Vec::new();
    for x in a..b {
        vec.push(x);
    }
    vec
}

live example on godbolt.org

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416