Search code examples
rustscopereturn

Scopes destroy value before I can return it (RUST)


I have this piece of code which essentially needs to return a String. I am iterating over a JSON response, and the value (the string that I am interested in) is deep inside it so I need to have a for loop and a if/else. The issue here is the scope {} of these loops. The value I am interested in gets destroyed right after the scope ends and the value I need to return becomes (), because the function returns a Result<String, reqwest::Error>

This is what I mean:

pub fn get_sprint() -> Result<String, reqwest::Error> {
    
    //The code to get the JSON response works fine. I store it in the variable called `get_request`. Here's the issue I am having:

    if get_request.status() == 200 {
        let resp: Response = get_request.json()?;
        for r in resp.value {
            if r.attributes.timeFrame == "current" {
                return Ok(r.name.to_string()); // THIS PLACE. I know the value is getting destroyed right after the scope ends, but I can't think of a way for it to not do that.
            }
        }

    } else {
        Ok(format!("Encountered error - {}", get_request.status().to_string()))
    }
}

When I run the above code, I get this:

error[E0308]: mismatched types
  --> src\getLatestSprint.rs:71:9
   |
37 |   pub fn get_sprint() -> Result<String, reqwest::Error> {
   |                          ------------------------------ expected `Result<std::string::String, reqwest::Error>` because of return type
...
71 | /         for r in resp.value {
72 | |             if r.attributes.timeFrame == "current" {
73 | |                 return Ok(r.name.to_string());
74 | |             }
75 | |         }
   | |_________^ expected enum `Result`, found `()`
   |
   = note:   expected enum `Result<std::string::String, reqwest::Error>`
           found unit type `()`

For more information about this error, try `rustc --explain E0308`.

Well, yes. I know it expects a Result, and got (). How can I get past this?


Solution

  • The error message does not mention a value getting destroyed. It says "you did not return anything at ALL".

    Your did not take into consideration all possibilities: If the response code is 200, bu the payload does NOT include timeFrame == "current", your method will return nothing.

    To solve this, add a return statement after your for loop.