Unable to return a vector of string slices: borrowed value does not live long enough

前端 未结 1 838
天命终不由人
天命终不由人 2021-01-13 15:57

I\'m new to Rust and I\'m having some trouble with the borrow checker. I don\'t understand why this code won\'t compile. Sorry if this is close to a previously answered ques

1条回答
  •  不知归路
    2021-01-13 16:40

    The problem is that you're allocating a new String (token_string) inside the lex function and then returning an array of references to it, but token_string will get dropped (and the memory freed) as soon as it falls out of scope at the end of the function.

    fn lex(s: &String) -> Vec<&str> {
        let token_string: String = s.replace("(", " ( ") // <-- new String allocated 
            .replace(")", " ) "); 
    
        let token_list: Vec<&str> = token_string.split_whitespace()
            .collect();
        token_list // <-- this is just an array of wide pointers into token_string
    } // <-- token_string gets freed here, so the returned pointers
      //     would be pointing to memory that's already been dropped!
    

    There's a couple of ways to address this. One would be to force the caller of lex to pass in the buffer that you want to use to collect into. This would change the signature to fn lex<'a>(input: &String, buffer: &'a mut String) -> Vec<&'a str> This signature would specify that the lifetimes of the returned &strs will be at least as long as the lifetime of the buffer that's passed in.

    Another way would be to just return a Vec instead of Vec<&str> if you can tolerate the extra allocations.

    0 讨论(0)
提交回复
热议问题