Unexpected static lifetime requirement for nested boxed closures with generic parameters
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.2k
- PR merge metrics
- PR metrics pending
Description
I tried this code:
type BoxedClosure<U> =
Box<dyn for<'e> Fn(&'e Context<'e, U>) -> bool + Sync + Send + 'static>;
pub struct CompiledExpr<U>(BoxedClosure<U>);
impl<U> CompiledExpr<U> {
pub fn new(
closure: impl for<'e> Fn(&'e Context<'e, U>) -> bool + Sync + Send + 'static,
) -> Self {
CompiledExpr(Box::new(closure))
}
}
pub struct Context<'e, U> {
data: &'e str,
userdata: U,
}
pub fn compile1<U>() -> CompiledExpr<U> {
CompiledExpr::new(|ctx| ctx.data == "rust")
}
pub fn compile2<U>() -> CompiledExpr<U> {
let e = compile1::<U>();
CompiledExpr::new(move |ctx| (e.0)(ctx))
}
I expected to see this happen: successful compilation
Instead, this happened:
error[E0310]: the parameter type `U` may not live long enough
--> src/lib.rs:25:5
|
25 | CompiledExpr::new(move |ctx| (e.0)(ctx))
| ^^^^^^^^^^^^^^^^^
| |
| the parameter type `U` must be valid for the static lifetime...
| ...so that the type `U` will meet its required lifetime bounds
|
help: consider adding an explicit lifetime bound
|
23 | pub fn compile2<U: 'static>() -> CompiledExpr<U> {
| +++++++++
I am not exactly sure its a bug per say, but from my perspective, this is relatively surprising that this code fails to build.
The 'static bound is on the boxed dyn object itself and not on the parameters of the boxed closure.
Its not clear why U should be 'static when Context which holds U is not.
Meta
rustc --version --verbose:
rustc 1.83.0 (90b35a623 2024-11-26)
binary: rustc
commit-hash: 90b35a6239c3d8bdabc530a6a0816f7ff89a0aaf
commit-date: 2024-11-26
host: x86_64-unknown-linux-gnu
release: 1.83.0
LLVM version: 19.1.1
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the linked Rust Playground example with the stable compiler version reported. Compare the generic compile1 and compile2 cases, then investigate the compiler behavior around the nested boxed closure and its inferred lifetime requirements. Done means determining whether the unexpected U: 'static requirement is correct or producing a focused compiler fix and regression coverage.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100