【问题标题】:Return original or modified str返回原始或修改后的 str
【发布时间】:2015-10-29 16:14:11
【问题描述】:

我有一个函数可以清理如下所示的字符串:

fn clean(s: &str) -> &str { // but not sure about return type
    if /* needs cleaning */ {
        let cleaned: String = s.chars().filter( /* etc */ ).collect();
        cleaned
    } else {
        s
    }
}

除非这不是书面的那样工作,因为清理的是String,而不是&str

这里的目标是只在必要时执行分配——如果字符串需要修改,我想用一个新的替换它,如果不需要,我不想调用to_string()在上面。理想情况下,我希望它对调用者是透明的,但不一定是 - 我也可以控制调用代码。即便如此,我还没有找到解决方法,因为如果新创建的String,甚至是借用它,在调用者中以某种 if 或 else 阻塞结束,它的生命周期还不够长在以其他方式使用原始字符串的上下文中使用。例如,这也不起作用:

fn caller(s: &str) {
    if needs_cleaning(s) {
        let cleaned = clean(s); // where clean always returns a new String
        s = &cleaned;
    }

    / * do stuff with the clean string */
}

这里的正确方法是什么?

【问题讨论】:

    标签: rust


    【解决方案1】:

    您正在寻找Cow:

    use std::borrow::Cow;
    
    fn clean(s: &str) -> Cow<str> {
        if /* needs cleaning */ {
            let cleaned: String = s.chars().filter(/* etc */).collect();
            Cow::Owned(cleaned)
        } else {
            Cow::Borrowed(s)
        }
    }
    

    【讨论】:

    • 你也可以只写cleaned.into()s.into()而不是显式命名枚举变量,因为String&amp;str都实现了Into&lt;Cow&lt;str&gt;&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 2020-02-27
    • 2019-12-05
    • 1970-01-01
    相关资源
    最近更新 更多