rust - explicit lifetime bound when using generic type - Stack Overflow

why explicit lifetime bound is required when using a generic type parameter in function print_v3 but no

why explicit lifetime bound is required when using a generic type parameter in function print_v3 but not in function print_v2 with concrete type parameter in the below code.

fn print_v2<'a>(list: impl IntoIterator<Item = &'a i32>) {
    for itr in list {
        print!("{}, ", itr);
    }
    println!("\n");
}

fn print_v3<'a, ItemType>(list: impl IntoIterator<Item = &'a ItemType>)
where
ItemType: 'a + std::fmt::Display
{
    for itr in list {
        print!("{}, ", itr);
    }
    println!("\n");
}

fn main() {
    let list = vec![1, 3, 5, 7, 9, 11, 11, 11, 11, 13, 15, 17, 19];

    print_v2(&list);
    print_v3(&list);
}

Error

error[E0309]: the parameter type `ItemType` may not live long enough
  --> src/main.rs:19:51
   |
19 | fn print_v3<'a, ItemType>(list: impl IntoIterator<Item = &'a ItemType>)
   |             --                                    ^^^^^^^^^^^^^^^^^^^ ...so that the reference type `&'a ItemType` does not outlive the data it points at
   |             |
   |             the parameter type `ItemType` must be valid for the lifetime `'a` as defined here...
   |
help: consider adding an explicit lifetime bound
   |
21 | ItemType: std::fmt::Display + 'a
   |                             ++++

error[E0309]: the parameter type `ItemType` may not live long enough
  --> src/main.rs:23:16
   |
19 | fn print_v3<'a, ItemType>(list: impl IntoIterator<Item = &'a ItemType>)
   |             -- the parameter type `ItemType` must be valid for the lifetime `'a` as defined here...
...
23 |     for itr in list {
   |                ^^^^ ...so that the type `ItemType` will meet its required lifetime bounds
   |
help: consider adding an explicit lifetime bound
   |
21 | ItemType: std::fmt::Display + 'a
   |                             ++++

For more information about this error, try `rustc --explain E0309`.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745269974a4619684.html

相关推荐

  • rust - explicit lifetime bound when using generic type - Stack Overflow

    why explicit lifetime bound is required when using a generic type parameter in function print_v3 but no

    2小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信