gpt4 book ai didi

rust - 临时u8切片的Rust字符串

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

我想运行一个命令并捕获其输出。

let result = match Command::new(thing.command).output() {
Ok(out) => String::from_utf8_lossy(&out.stdout),
Err(_) => ....,
};
我收到 &out.stdoutborrowed value does not live long enough错误。我理解这个问题,但是如何创建u8 slice的副本并将完整所有权转移到新创建的字符串中?

最佳答案

from_utf8_lossy的返回值是Cow:pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str>如果要创建副本并转让所有权,into_owned()Cow是专门为此设计的:

pub fn into_owned(self) -> <B as ToOwned>::Owned
Extracts the owned data.

Clones the data if it is not already owned.

关于rust - 临时u8切片的Rust字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65858051/

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