Return local String as a slice (&str)

后端 未结 5 1580
温柔的废话
温柔的废话 2020-11-21 06:27

There are several questions that seem to be about the same problem I\'m having. For example see here and here. Basically I\'m trying to build a String in a loca

5条回答
  •  囚心锁ツ
    2020-11-21 07:17

    The problem is that you are trying to create a reference to a string that will disappear when the function returns.

    A simple solution in this case is to pass in the empty string to the function. This will explicitly ensure that the referred string will still exist in the scope where the function returns:

    fn return_str(s: &mut String) -> &str {
    
        for _ in 0..10 {
            s.push_str("ACTG");
        }
    
        &s[..]
    }
    
    fn main() {
        let mut s = String::new();
        let s = return_str(&mut s);
        assert_eq!("ACTGACTGACTGACTGACTGACTGACTGACTGACTGACTG", s);
    }
    

    Code in Rust Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=2499ded42d3ee92d6023161fe82e9b5f

提交回复
热议问题