简体   繁体   中英

How to declare a generic function with a trait bound that is parameterized with a lifetime name?

Given a generic function:

fn foo<T> (_x: T) {}

I'd like to add a serde::Deserialize trait bound. However the following

fn foo<T: serde::Deserialize> (_x: T) {}

results in

error[E0637]: `&` without an explicit lifetime name cannot be used here
 --> src/lib.rs:1:11
  |
1 | fn foo<T: serde::Deserialize> (_x: T) {}
  |           ^^^^^^^^^^^^^^^^^^ explicit lifetime name needed here

And trying it like I understand the serde documentation regarding deserializer lifetimes

fn foo<'de, T> where T: serde::Deserialize<'de> (_x: T) {}

also yields an error:

error: expected `(`, found `where`
 --> src/lib.rs:1:16
  |
1 | fn foo<'de, T> where T: serde::Deserialize<'de> (_x: T) {}
  |                ^^^^^ expected `(`

What am I doing wrong?

Oh, it was just a basic error in the function syntax.

fn foo<'de, T>(_x: T)
where
    T: serde::Deserialize<'de>,
{
    // ...
}

is correct and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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