首页 > 解决方案 > Rust:返回一个引用当前函数拥有的数据的值

问题描述

我有一小段代码。为什么第二个编译失败?

fn apply (&self, text: Text) -> Text {
    // works fine
    let mut data = String::new();
    for c in text.data.chars() {
        let c = *self.mapping.get(&c).unwrap_or(&c);
        data.push(c);
    }
    return Text {
        data,
    };

    // not compile
    return Text {
        data: text.data.chars().map(|c| self.mapping.get(&c).unwrap_or(&c)).collect(),
    };
}

标签: rustcompiler-errorsiterator

解决方案


编译器会告诉您确切的原因(这就是阅读和发布编译错误很有用的原因:

8 |             data: text.data.chars().map(|c| self.mapping.get(&c).unwrap_or(&c)).collect()
  |                                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^--^
  |                                             |                              |
  |                                             |                              `c` is borrowed here
  |                                             returns a value referencing data owned by the current function

在映射中不存在输入的情况下char,它会返回对局部变量的引用,这是不允许的,因为......然后该引用将悬空,这是 rust 不允许的。

该解决方案与“正常工作”版本中使用的解决方案完全相同:取消引用回调的结果,该结果将Copy指向&chara char,它是拥有的,因此可以在没有生命周期的情况下返回:

        Text {
            data: text.data.chars().map(|c| *self.mapping.get(&c).unwrap_or(&c)).collect()
        }

或者,您可以产生一个'd to 'copied的结果,出于相同的原因解决问题:HashMap::getOption<char>unwrap_orchar

        Text {
            data: text.data.chars().map(|c| self.mapping.get(&c).copied().unwrap_or(c)).collect()
        }

推荐阅读