我正在尝试返回 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/