函数返回Vec

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

我试图返回&str的向量但是在尝试将u64转换为while循环中的&str时遇到了问题。

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
}

无法返回引用临时值的值

如果我只返回一个字符串向量,那么它工作正常。

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 of 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(),
    }
}
rust
1个回答
2
投票

你介绍的生命周期是说“我正在返回一个字符串引用的向量,它的生命周期超过了这个函数”。事实并非如此,因为您正在创建一个String,然后存储对它的引用。该引用将在创建String的范围结束时死亡。

仅仅从“设计”POV回答你的问题:

我应该返回一个Vec <&str>还是只返回一个Vec of String类型并让调用者处理转换?

该方法称为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引用向量的函数的更多信息更新您的问题,我可以更新我的答案以帮助重新设计它。

© www.soinside.com 2019 - 2024. All rights reserved.