如何在我的代码中使用拥有的数据。借来的价值无法生存

时间:2018-09-08 19:25:23

标签: rust lifetime borrowing

我坚持下面的代码:

pub fn get_all<'a>() -> Vec<DesktopEntry<'a>> {
    let all_desktop_files = filesystem::get_all_desktop_files();

    all_desktop_files
        .into_iter()
        .filter_map(|desktop_file| {
            let ini_option = load_ini(desktop_file);

            match ini_option {
                Some(ini) => convert_ini_to_desktop_entry(&ini), // <--
                None => None,
            }
        }).collect::<Vec<DesktopEntry>>()
}

fn convert_ini_to_desktop_entry<'a>(ini: &'a Ini) -> Option<DesktopEntry> {
    let section = match ini.section(Some("Desktop Entry")) {
        Some(s) => Some(s),
        None => None,
    };

    let name = match section {
        Some(s) => match s.get("Name") {
            Some(p) => Some(p),
            None => None,
        },
        None => None,
    };

    Some(DesktopEntry {
        name: name.unwrap(),
    })
}

还有&ini生命周期中的错误:

borrowed value does not live long enough
...note: borrowed value must be valid for the lifetime 'a as defined on the function body at 10:5...

我了解到&ini的生存时间不长。但是我真的不明白如何解决它。本书中建议如何修复:

the best fix would be to return an owned data type rather than a reference

但是convert_ini_to_desktop_entry函数的结果和参数需要使用期限。而且我不明白,为什么此功能中的ini不能拥有价值。

0 个答案:

没有答案