gpt4 book ai didi

rust - 使用谓词返回引用时存在生命周期冲突(使用谓词实现 “split at mut”)

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

这里是否可以分配生命周期,这样即使对于谓词返回引用也可以实现这样的功能?

fn group_by_into_slices_mut<'a, T, F, K>(data: &'a mut [T], key: F, res: &mut Vec<&'a mut [T]>)
where
K: PartialEq,
F: Fn(&T) -> K + 'static,
{
let mut data = data;
while !data.is_empty() {
let j = find_j(&data, &key);
let (s1, s2) = data.split_at_mut(j);
res.push(s1);
data = s2;
}
}

fn find_j<'a, T, F, K>(data: &'a [T], key: &F) -> usize
where
K: PartialEq,
F: Fn(&T) -> K + 'static,
{
let current_key = key(&data[0]);
for i in 1..data.len() {
if current_key != key(&data[i]) {
return i;
}
}
data.len()
}


struct Struct {
key: String,
}

fn main() {
let v = vec![Struct { key: "abc".to_string() }];
let res = vec![];
group_by_into_slices_mut(&mut v, |e| &e.key, &mut res);
}
  --> src/main.rs:37:42
|
37 | group_by_into_slices_mut(&mut v, |e| &e.key, &mut res);
| ^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 37:38...
--> src/main.rs:37:38
|
37 | group_by_into_slices_mut(&mut v, |e| &e.key, &mut res);
| ^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:37:42
|
37 | group_by_into_slices_mut(&mut v, |e| &e.key, &mut res);
| ^^^^^^
note: but, the lifetime must be valid for the expression at 37:5...
--> src/main.rs:37:5
|
37 | group_by_into_slices_mut(&mut v, |e| &e.key, &mut res);
| ^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so type `for<'a, 'r> fn(&'a mut [Struct], [closure@src/main.rs:37:38: 37:48], &'r mut std::vec::Vec<&'a mut [Struct]>) {group_by_into_slices_mut::<Struct, [closure@src/main.rs:37:38: 37:48], &std::string::String>}` of expression is valid during the expression
--> src/main.rs:37:5
|
37 | group_by_into_slices_mut(&mut v, |e| &e.key, &mut res);
| ^^^^^^^^^^^^^^^^^^^^^^^^

我不确定为什么这行不通。我试图明确地添加一些生命,包括更高等级的特质界限,但是没有运气。

操场:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1663e12bf67838dd0d1440f759a72b4e

最佳答案

解决方案1:
我认为如果不像现在的特征范围那样将"abc"保留为&'static str,就不可能实现。如果可以将Struct对象更改为此:

struct Struct<'a> {
key: &'a str
}

fn main() {
let _ = Struct { key: "abc" }; //never convert "abc" to an owned type
}
...并将您的闭包作为 |e| e.key而不是 |e| &e.key传递,然后您的代码可以正常编译。
函数实现不会改变,谓词仍会返回引用,但是现在 'static的引用已存在。 |e| &e.key闭包将不起作用,因为仅允许闭包主体存在返回的引用。
解决方案2:
删除两个 'static特征上的 F界限,并将闭包更改为 |e| e.key.clone(),但是我想这不是您要查找的内容,因为您将不再返回引用。

关于rust - 使用谓词返回引用时存在生命周期冲突(使用谓词实现 “split at mut”),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61333827/

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