Skip to content

schedule_relative! macro requires type annotations for closure handlers #956

Open

Description

@RobertJacobsonCDC

The current schedule_relative! macro can fail to compile when the handler is an unannotated closure.

For example, this kind of invocation does not compile:

schedule_relative!(context, delay, |context| {
    let t = context.get_current_time();
    trace!("event ran at t={t}");
});

The compiler reports:

error[E0282]: type annotations needed
  --> examples/network-hhmodel/seir.rs:55:41
   |
55 |     schedule_relative!(context, delay, |context| {
   |                                         ^^^^^^^
56 |         let t = context.get_current_time();
   |                 ------- type must be known at this point

Adding an explicit type annotation works:

schedule_relative!(context, delay, |context: &mut Context| {
    let t = context.get_current_time();
    trace!("event ran at t={t}");
});

Function handlers are not affected:

fn do_event(context: &mut Context, person_id: PersonId) {
    let t = context.get_current_time();
    trace!("{person_id:?} event ran at t={t}");
}

schedule_relative!(context, delay, do_event, person_id);

Why this happens:

The macro wraps the supplied handler in another closure before passing it to add_plan. The outer closure parameter is typed as &mut Context, but that does not give an expected type to the parameter of the user-supplied closure. As a result, when Rust checks the body of |context| { ... }, it does not yet know the type of context, so method calls like context.get_current_time() cannot be resolved. Unfortunately, the Rust compiler does not use the arguments that the closure is immediately called with to infer the parameter type in this case, so the fact that we are typing the outer closure doesn't resolve this issue.

This issue is to improve the ergonomics for closure handlers so users do not need to write |context: &mut Context| in this case.

Activity

  1. changed the title [-]Fix closure parameter type inferrence issue in `schedule_relative!` macro[/-] [+]`schedule_relative!` macro requires type annotations for closure handlers[/+] on Jun 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions