The compiler behaves strangely. For a given lifetime, if it bounds itself ('a: 'a), it will compile, otherwise it will not. I think it is a bug that this subtle difference can change whether it can be compiled or not.
I tried this code:
fn main() {
let wrapped_vec = WrappedVec {
vec: vec!["1"],
};
let first = first_str_len(wrapped_vec);
println!("first: {}", first);
}
struct WrappedVec<'a> {
vec: Vec<&'a str>,
}
impl<'a> WrappedVec<'a> {
fn iter(&'a self) -> impl Iterator<Item=&'a &'a str> {
self.vec.iter()
}
}
fn first_str_len<'a>(arg: WrappedVec<'a>) -> usize {
let first = arg.iter().next().unwrap();
let return_arg = |str: &'a str| -> &'a str {
str
};
return_arg(first).len()
}
This code does not compile.
error[E0597]: `arg` does not live long enough
--> src/main.rs:21:17
|
20 | fn first_str_len<'a>(arg: WrappedVec<'a>) -> usize {
| -- lifetime `'a` defined here
21 | let first = arg.iter().next().unwrap();
| ^^^-------
| |
| borrowed value does not live long enough
| argument requires that `arg` is borrowed for `'a`
...
28 | }
| - `arg` dropped here while still borrowed
For more information about this error, try `rustc --explain E0597`.
You can compile it by rewriting the part shown below.
fn first_str_len<'a>(arg: WrappedVec<'a>) -> usize {
// ↓ <'a> -> <'a: 'a>
fn first_str_len<'a: 'a>(arg: WrappedVec<'a>) -> usize {
The code is unnatural because it was rebuilt by extracting only the parts that seemed necessary for replication from the code where the problem was found.
Meta
rustc --version --verbose:
rustc 1.55.0 (c8dfcfe04 2021-09-06)
binary: rustc
commit-hash: c8dfcfe046a7680554bf4eb612bad840e7631c4b
commit-date: 2021-09-06
host: x86_64-pc-windows-msvc
release: 1.55.0
LLVM version: 12.0.1
I tried it in the Rust playground, and the same thing happened in beta and nightly.
https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=05a374855198719d56d41ac02be0d59e
Backtrace
There was no backtrace
The compiler behaves strangely. For a given lifetime, if it bounds itself (
'a: 'a), it will compile, otherwise it will not. I think it is a bug that this subtle difference can change whether it can be compiled or not.I tried this code:
This code does not compile.
You can compile it by rewriting the part shown below.
The code is unnatural because it was rebuilt by extracting only the parts that seemed necessary for replication from the code where the problem was found.
Meta
rustc --version --verbose:I tried it in the Rust playground, and the same thing happened in beta and nightly.
https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=05a374855198719d56d41ac02be0d59e
Backtrace
There was no backtrace