Return local String as a slice (&str)

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

    In certain cases, you are passed a string slice and may conditionally want to create a new string. In these cases, you can return a Cow. This allows for the reference when possible and an owned String otherwise:

    use std::borrow::Cow;
    
    fn return_str<'a>(name: &'a str) -> Cow<'a, str> {
        if name.is_empty() {
            let name = "ACTG".repeat(10);
            name.into()
        } else {
            name.into()
        }
    }
    

提交回复
热议问题