Skip to content

Commit f2451d9

Browse files
authored
Merge pull request Rust-for-Linux#60 from Rust-for-Linux/dev/lifetime-test
tests: ui: add new tests for lifetime violations
2 parents 3858747 + d4d83a5 commit f2451d9

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
use pin_init::{init, InPlaceInit, Init};
2+
3+
#[derive(Debug)]
4+
struct Foo {
5+
a: i32,
6+
}
7+
8+
impl Foo {
9+
fn new(val: &i32) -> impl Init<Self> + use<'_> {
10+
init!(Self { a: *val })
11+
}
12+
}
13+
14+
#[derive(Debug)]
15+
struct Bar {
16+
foo: Foo,
17+
}
18+
19+
impl Bar {
20+
fn new(foo: impl Init<Foo>) -> impl Init<Self> {
21+
init!(Self { foo <- foo })
22+
}
23+
}
24+
25+
fn main() {
26+
// problematic:
27+
let foo;
28+
{
29+
let val = 42;
30+
foo = Foo::new(&val);
31+
}
32+
let bar = Box::init(Bar::new(foo));
33+
println!("{bar:?}");
34+
35+
// okay:
36+
let val = 42;
37+
let foo = Foo::new(&val);
38+
let bar = Box::init(Bar::new(foo));
39+
println!("{bar:?}");
40+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
error[E0597]: `val` does not live long enough
2+
--> tests/ui/compile-fail/init/lifetime_violated.rs:30:24
3+
|
4+
29 | let val = 42;
5+
| --- binding `val` declared here
6+
30 | foo = Foo::new(&val);
7+
| ^^^^ borrowed value does not live long enough
8+
31 | }
9+
| - `val` dropped here while still borrowed
10+
32 | let bar = Box::init(Bar::new(foo));
11+
| --- borrow later used here

0 commit comments

Comments
 (0)