|
| 1 | +An argument lifetime was elided in an async function. |
| 2 | + |
| 3 | +Erroneous code example: |
| 4 | + |
| 5 | +When a struct or a type is bound/declared with a lifetime it is important for |
| 6 | +the Rust compiler to know, on usage, the lifespan of the type. When the |
| 7 | +lifetime is not explicitly mentioned and the Rust Compiler cannot determine |
| 8 | +the lifetime of your type, the following error occurs. |
| 9 | + |
| 10 | +```compile_fail,E0726 |
| 11 | +use futures::executor::block_on; |
| 12 | +struct Content<'a> { |
| 13 | + title: &'a str, |
| 14 | + body: &'a str, |
| 15 | +} |
| 16 | +async fn create(content: Content) { // error: implicit elided |
| 17 | + // lifetime not allowed here |
| 18 | + println!("title: {}", content.title); |
| 19 | + println!("body: {}", content.body); |
| 20 | +} |
| 21 | +let content = Content { title: "Rust", body: "is great!" }; |
| 22 | +let future = create(content); |
| 23 | +block_on(future); |
| 24 | +``` |
| 25 | + |
| 26 | +Specify desired lifetime of parameter `content` or indicate the anonymous |
| 27 | +lifetime like `content: Content<'_>`. The anonymous lifetime tells the Rust |
| 28 | +compiler that `content` is only needed until create function is done with |
| 29 | +it's execution. |
| 30 | + |
| 31 | +The `implicit elision` meaning the omission of suggested lifetime that is |
| 32 | +`pub async fn create<'a>(content: Content<'a>) {}` is not allowed here as |
| 33 | +lifetime of the `content` can differ from current context: |
| 34 | + |
| 35 | +```ignore (needs futures dependency) |
| 36 | +async fn create(content: Content<'_>) { // ok! |
| 37 | + println!("title: {}", content.title); |
| 38 | + println!("body: {}", content.body); |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | +Know more about lifetime elision in this [chapter][lifetime-elision] and a |
| 43 | +chapter on lifetimes can be found [here][lifetimes]. |
| 44 | + |
| 45 | +[lifetime-elision]: https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-elision |
| 46 | +[lifetimes]: https://doc.rust-lang.org/rust-by-example/scope/lifetime.html |
0 commit comments