Increase lifetime of borrowed value - "Borrowed value does not live long enough"

Hello there,

I'm facing a problem which I only understand superficially. Here's a code snippet:

fn handle_msg(mut msg: String, session: &Session, mut selected_branch: &str) -> Option<String> {
    msg = msg.replace("\n", "");
    if msg.starts_with("SET BRANCH") {
        // PROBLEMATIC LINE
        selected_branch = msg.split(" ").nth(2).unwrap();
    }

    match msg.as_str() {
    // ...

The statement selected_branch = msg.split(" ").nth(2).unwrap(); throws the following compiler error: "Borrowed value does not live long enough

I assume the error means that the result of msg.split(" ").nth(2).unwrap(); is borrowed by selected_branch - is this the case?
Anyway, how do I solve this problem?

Many thanks!

The problem is that the selected_branch variable lives longer than msg, so it can't contain a reference to msg. (I was a little surprised by this, since I wasn’t familiar with how ordering of function parameters affects their scopes.)

One solution is to store the reference in a new variable with a shorter scope. You can give the new variable the same name and it will “shadow” the original:

fn handle_msg(mut msg: String, session: &Session, selected_branch: &str) -> Option<String> {
    msg = msg.replace("\n", "");
    let selected_branch = if msg.starts_with("SET BRANCH") {
        msg.split(" ").nth(2).unwrap()
    } else {
        selected_branch
    };
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.