Skip to content

(values_of) cannot return value referencing local variable matches #2107

Answered by CreepySkeleton
nbari asked this question in Q&A
Discussion options

You must be logged in to vote

Short answer: matches is a local variable, value_of borrows from it and therefore the returned &str reference must not outlive matches, but you're trying to return the ref while matches will be dropped when execution reaches the end of the function, so the ref will become invalid. The solution is to return Vec<String> - no references, no problems (and a slight perf penalty you won't even notice).

Long answer: I think you have just yet to comprehend rust borrowing rules and lifetimes. See the book: https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#dangling-references

Replies: 2 comments 5 replies

Comment options

You must be logged in to vote
0 replies
Answer selected by pksunkara
Comment options

You must be logged in to vote
5 replies
@CreepySkeleton
Comment options

@CreepySkeleton
Comment options

@nbari
Comment options

@CreepySkeleton
Comment options

@nbari
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants