admin管理员组

文章数量:1122832

I've simplified my code to

mod fail {
    use std::borrow::Cow;
    
    pub struct C<'a>(Cow<'a, [&'a ()]>);
    struct CWrapper<'a>(&'a C<'a>);
    
    pub fn foo(c: &C) {
        let _ = CWrapper(c);
    }
}

mod ok_std_cow {
    use std::borrow::Cow;
    
    pub struct C<'a>(Cow<'a, [()]>);
    struct CWrapper<'a>(&'a C<'a>);
    
    pub fn foo(c: &C) {
        let _ = CWrapper(c);
    }
}

mod ok_my_cow {
    enum MyCow<'a> {
        Borrowed(&'a [&'a ()]),
        Owned(Vec<&'a ()>),
    }
    pub struct C<'a>(MyCow<'a>);
    struct CWrapper<'a>(&'a C<'a>);
    
    pub fn foo(c: &C) {
        let _ = CWrapper(c);
    }
}

>> Playground

error: lifetime may not live long enough
 --> src/lib.rs:8:26
  |
7 |     pub fn foo(c: &C) {
  |                -  - let's call the lifetime of this reference `'1`
  |                |
  |                has type `&fail::C<'2>`
8 |         let _ = CWrapper(c);
  |                          ^ this usage requires that `'1` must outlive `'2`
  |
help: consider introducing a named lifetime parameter
  |
7 |     pub fn foo<'a>(c: &'a C<'a>) {
  |               ++++     ++  ++++

Questions:

  1. Why does the fail::foo function emit error?
  2. Could I fix it without introducing changes to the function signature of foo and the generic list of struct C, and without reimplementing Cow?

本文标签: rustLifetime may not live long enough when Cow39s generic type contains lifetimeStack Overflow