Rust 为什么可以';t我返回一个向量<&;str>;从一个函数?

Rust 为什么可以';t我返回一个向量<&;str>;从一个函数?,rust,Rust,我试图返回Vec,但在while循环中将u64转换为&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) { s

我试图返回
Vec
,但在while循环中将
u64
转换为
&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
}

您介绍的生存期是“我返回一个字符串引用向量,其生存期超过此函数”。这不是真的,因为您正在创建一个
字符串
,然后存储对它的引用。该引用将在创建
字符串的范围结束时终止

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

我应该返回一个Vec,还是只返回一个字符串类型的Vec,让调用方处理转换

该方法称为
latest\u id
。。你要传递的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
}
fn main()->std::io::Result{
let-id:Vec=latest_-id(5,10).iter().map(|n | n.to_-string()).collect();
让ids作为字符串引用:Vec=ids.iter().map(|n |&**n.collect();
println!(“{:?}”,id作为字符串引用);
好(())
}
fn最新\u id(当前\u id:u64,最新\u id:u64)->Vec{
让mut id=vec![];
让mut启动=当前\u id;
while!(开始>=最新的\u id){
开始+=1;
id.push(启动);
}
身份证
}
打印:
[“6”、“7”、“8”、“9”、“10”]


这里的双重处理是因为你要求推荐人。根据代码周围的上下文,可能不需要双重处理。如果您更新了您的问题,并提供了下一个需要
&str
参考向量的函数的更多信息,我可以更新我的答案以帮助重新设计它。

感谢您的详细回复。我已经用调用的下一个方法更新了这个问题。这些整数ID的传递到底有多远?最干净的方法可能是一直向下传递一个整数向量,直到该向量被迭代,然后根据循环中的需要将其转换为
&str
。它不再向下传递任何级别。我认为add_queue应该进行转换,就像meta_handler.one()一样。add_fetch_queue(ids)。execute()由其他函数使用,其中原始ID是字母数字。你怎么看?老实说,如果不把它作为一个整体来看待,给出建议有点难。也就是说,我的建议是尽可能地在调用堆栈的底层进行双重处理/转换。如果在
add_queue
中执行此操作是您认为它应该位于的位置,那么这听起来不错。
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(),
    }
}
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
}