0

I'm new in Rust, I'm doing my first steps by resolving exercises on https://exercism.org/.

I'm creating a method that finds a MatchDetails in a vector, if it exists then returns the reference of this instance otherwise returns the reference of a new instance of MatchDetails.

It happens that MatchDetails::with_team_name(team_name) returns a new instance of MatchDetails based on a team_name and I want to use the reference returns from this MatchDetails::with_team_name(team_name).

pub fn get_team(match_details: &Vec<MatchDetails>, team_name: String) -> &MatchDetails {
    let team = match_details.iter().find(|md| md.team_name == team_name);
    match team {
        Some(match_detail) => match_detail,
        None => MatchDetails::with_team_name(team_name),
    }
}

In the None match I would like to return something like &MatchDetails::with_team_name(team_name) but I get the following error:

cannot return value referencing temporary value returns a value referencing data owned by the current function

cafce25
  • 15,907
  • 4
  • 25
  • 31
JaimeCamargo
  • 353
  • 1
  • 3
  • 14
  • 1
    You can't return a reference to a local, so you'll need to re-think this. In Rust, it's often better to return `None` and let the caller do `.unwrap_or_else(|| MatchDetails::with_team_name(team_name))` where that's their problem. – tadman Mar 06 '23 at 23:45
  • 3
    Side note: [You should accept `&[MatchDetails]` instead of `&Vec`](https://stackoverflow.com/questions/40006219/why-is-it-discouraged-to-accept-a-reference-string-vec-or-box-as-a-function) – cafce25 Mar 06 '23 at 23:48
  • Even better, accept `impl IntoIterator` (you will need to introduce `'a` as a generic argument. – cdhowie Mar 07 '23 at 01:41
  • @cdhowie Given that that's best, I sure wish there was a more concise way to specify that :D – cadolphs Mar 07 '23 at 04:03

0 Answers0