rust - 为什么我不能从函数返回 Vec<&str>?

标签 rust

我正在尝试返回 Vec<&str>但在转换 u64 时遇到问题至 &str在 while 循环中:

fn latest_ids<'a>(current_id: u64, latest_id: u64) -> Vec<&'a str> {
    let mut ids: Vec<&str> = vec![];
    let mut start = current_id;
    while !(start >= latest_id) {
        start += 1;
        ids.push(start.to_string().as_str());
    }
    ids
}

cannot return value referencing temporary value

如果我只返回一个 Vec<String>然后就可以正常工作了。

fn latest_ids<'a>(current_id: u64, latest_id: u64) -> Vec<String> {
    let mut ids: Vec<String> = vec![];
    let mut start = current_id;
    while !(start >= latest_id) {
        start += 1;
        ids.push(start.to_string());
    }
    ids
}

在此之后调用的下一个函数需要 &str类型参数所以我应该返回 Vec<&str>或者只返回 Vec<String>让调用者处理转换?

在得到 latest_ids() 的结果后要调用的下一个函数:

pub fn add_queue(job: &Job, ids: Vec<&str>) -> Result<(), QueueError> {
    let meta_handler = MetaService {};

    match job.meta_type {
        MetaType::One => meta_handler.one().add_fetch_queue(ids).execute(),
        MetaType::Two => meta_handler.two().add_fetch_queue(ids).execute(),
        MetaType::Three => meta_handler.three().add_fetch_queue(ids).execute(),
    }
}

最佳答案

你引入的生命周期是说“我正在返回一个字符串引用向量,它的生命周期超过了这个函数”。这不是真的,因为您正在创建一个 String 然后存储对它的引用。该引用将在创建 String 的范围末尾消失。

纯粹从“设计”POV 回答您的问题:

should I be returning a Vec<&str> or just return a Vec of String type and let the caller handle the conversion?

该方法称为 latest_ids .. 您传递的 ID 是 64 位整数。考虑到您应该返回 64 位整数并且调用者应该进行转换的方法名称,我认为这是可以接受的。

fn main() -> std::io::Result<()> {

    let ids: Vec<String> = latest_ids(5, 10).iter().map(|n| n.to_string()).collect();
    let ids_as_string_references: Vec<&str> = ids.iter().map(|n| &**n).collect();

    println!("{:?}", ids_as_string_references);

    Ok(())
}

fn latest_ids(current_id: u64, latest_id: u64) -> Vec<u64> {
    let mut ids = vec![];
    let mut start = current_id;
    while !(start >= latest_id) {
        start += 1;
        ids.push(start);
    }
    ids
}

打印:["6", "7", "8", "9", "10"]

此处的双重处理是因为您要求提供引用。根据代码的进一步上下文,可能不需要双重处理。如果您使用有关需要 &str 引用向量的下一个函数的更多信息更新您的问题,我可以更新我的答案以帮助重新设计它。

关于rust - 为什么我不能从函数返回 Vec<&str>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55931401/

相关文章:

bash - 如何完成 rustup/cargo 命令?

rust - 尝试从包含在 RefCell 中的结构中借用 2 个字段时出错

rust - ManuallyDrop<Box<T>> 是否具有 mem::uninitialized 定义的行为?

rust - 在带有 CPU arm926ej-s 的板上运行交叉编译的 HelloWorld 到 armv5te 时出现段错误

rust - 构建完成后复制文件到目标目录

methods - 如何在方法中将结构的数据分配给自身?

sockets - 无法从外部机器连接到 TCP 服务器

rust - 如何将一个字段移出实现 Drop 特性的结构?

rust - Rust 中函数的类型同义词

types - 在 Rust 的 32 位机器中,f64 类型是如何表示的?