繁体   English   中英

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

[英]Conflicting lifetimes when using predicate returning reference (implementing “split at mut” with predicate)

有没有办法在这里分配生命周期,这样即使对于返回引用的谓词也可以实现这样的 function ?

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代替|e| &e.key |e| &e.key然后你的代码编译得很好。

function 实现没有改变,谓词仍然返回一个引用,但现在该引用存在于'static 一个|e| &e.key |e| &e.key闭包不起作用,因为返回的引用只允许存在于闭包的主体中。

解决方案2:

删除两个F特征上的'static边界并将闭包更改为|e| e.key.clone() |e| e.key.clone() ,但我猜这不是你要找的,因为你不会再返回参考了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM