Return local String as a slice (&str)

后端 未结 5 1586
温柔的废话
温柔的废话 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 06:59

    You can choose to leak memory to convert a String to a &'static str:

    fn return_str() -> &'static str {
        let string = "ACTG".repeat(10);
    
        Box::leak(string.into_boxed_str())
    }
    

    This is a really bad idea in many cases as the memory usage will grow forever every time this function is called.

    If you wanted to return the same string every call, see also:

    • How to create a static string at compile time

提交回复
热议问题