gpt4 book ai didi

rust - 如何修复Rust中无法返回引用函数参数错误的值

转载 作者:行者123 更新时间:2023-12-03 11:34:09 25 4
gpt4 key购买 nike

目的是获取调用二进制文件的输出,获取该输出的最后一行,将其拆分,然后从索引1获得字符串。

这是尝试:

    let result:Result<String, FromUtf8Error> = String::from_utf8(output.stdout);
let value = result.map(move |res| {
res.lines()
.last()
.unwrap_or(String::from("").as_ref())
.split(" ")
.collect::<Vec<&str>>()[1]
});

两个问题:

首先,上面的代码导致编译错误:
57 | /         res.lines()
58 | | .last()
59 | | .unwrap_or(String::from("").as_ref())
| | ---------------- temporary value created here
60 | | .split(" ")
61 | | .collect::<Vec<&str>>()[1]
| |______________________________________^ returns a value referencing data owned by the current function

第二个,我意识到 value的类型是 Result<<unknown>,FromUtf8Error>而不是我期望的 Result<<String>,FromUtf8Error>

那么,如何解决编译错误并获得正确的类型呢?

最佳答案

您试图返回的&str指向map闭包所拥有的数据。
与...相同

fn does_not_work() -> &str {
let my_string = String::new();
&my_string
}

您需要拥有一个拥有的值(value)(例如 String)才能返回。
result.map(move |res| {
String::from(
res.lines()
.last()
.unwrap_or("")
.split(" ")
.collect::<Vec<&str>>()[1]
)
})

关于rust - 如何修复Rust中无法返回引用函数参数错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62243005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com