字符串转换为str切片,str切片存在的时间不够长



好,这是我的MCVE,马上。

fn do_something (string: &'static str) -> Result<&str, isize> {
    Ok(string)
}
fn main() {
    let place = Some("hello".to_string());
    match place {
        Some(input) => {
            let place = &input[..];
            let something = do_something(place);
        }
        _ => (),
    }
}

我似乎不能想出一个方法来满足do_something。在我的实际代码中,do_something是一个库函数,所以我不能改变它的签名。

——由于

如果不能更改函数的签名,则需要使用字符串文字来创建&'static str或泄漏内存。

。或者这样做:

do_something("hello");

或者这个(坏主意,可能会坏,只在夜间工作):

let place = Some("hello".to_string());
if let Some(s) = place {
    do_something(unsafe { std::mem::transmute(s.into_boxed_str()) });
}

相关内容

最新更新