如何正确返回临时值的引用?

问题描述 投票:0回答:1

例如,这个函数按预期工作:

fn get_suffix(str: Option<&str>) -> u32 {
    str.and_then( |s| s.rsplit('_').next() )
       .and_then( |s| s.parse::<u32>().ok() )
       .unwrap_or(0)
}

但这给了我编译错误:

fn get_suffix_from_path(path: &Path) -> u32 {
    path.file_stem()
        .and_then( |s| s.to_string_lossy().rsplit('_').next() )
        .and_then( |s| s.parse::<u32>().ok() )
        .unwrap_or(0)
}
328 |                     stem.to_string_lossy().rsplit('_').next())
    |                     ----------------------^^^^^^^^^^^^^^^^^^^
    |                     |
    |                     returns a value referencing data owned by the current function
    |                     temporary value created here

我不完全确定这意味着什么。是因为

to_string_lossy()
创建了
String
,并且在关闭结束时会立即删除吗?解决这个问题的惯用方法是什么?

我试过这个:

stem.to_string_lossy().rsplit('_').next().and_then(|s| Some(s.to_owned()) )

它可以工作,但它不仅丑陋,而且不必要地复制字符串。

rust closures borrow-checker
1个回答
0
投票

你是对的:

Cow<str>
提供的
.to_string_lossy()
必须存在,直到你解析它的内容并获得一个整数。

您只需在存在此

Cow<str>
的闭包内执行解析即可。

use std::path::Path;

fn get_suffix_from_path(path: &Path) -> u32 {
    path.file_stem()
        .and_then(|s| {
            s.to_string_lossy()
                .rsplit('_')
                .next()
                .and_then(|s| s.parse().ok())
        })
        .unwrap_or(0)
}

fn main() {
    let p = Path::new("/tmp_56");
    let s = get_suffix_from_path(&p);
    println!("{:?} {:?}", p, s);
}
/*
"/tmp_56" 56
*/
© www.soinside.com 2019 - 2024. All rights reserved.