2

I am running into some trouble when trying to return a string. I have been trying various ways of defining my variables and return value to try and make it so I can return the string primitive, but I get an array of lifetime related error messages.

pub fn raindrops(int: u64) -> &'a str {
    let mut out = String::new();

    if int % 3 == 0 {
        out.push_str("Pling");
    }
    if int % 5 == 0 {
        out.push_str("Plang");
    }
    if int % 7 == 0 {
        out.push_str("Plong");
    }
    if out.is_empty() {
        out.push_str(&format!("{}", int));
    }

    out.shrink_to_fit();

    return out.as_str();
}

Error:

error[E0261]: use of undeclared lifetime name `'a`
 --> src/lib.rs:1:32
  |
1 | pub fn raindrops(int: u64) -> &'a str {
  |                                ^^ undeclared lifetime

error: aborting due to previous error

error: Could not compile `raindrops`.
Build failed, waiting for other jobs to finish...
error[E0261]: use of undeclared lifetime name `'a`
 --> src/lib.rs:1:32
  |
1 | pub fn raindrops(int: u64) -> &'a str {
  |                                ^^ undeclared lifetime
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
gangwerz
  • 435
  • 2
  • 8
  • 18

1 Answers1

4

You can't return a &str in this situation, because it would point to the contents of out which goes out of scope at the end of the function. You have to return the String out instead.

Alternatively, if you want to limit allocations, you could return an enum which can be one of:

Pling,
Plang,
Plong,
Other(u64)

and then print the response based on the value.

viraptor
  • 33,322
  • 10
  • 107
  • 191