genericsrust

How to define a const closure inside a generic struct


I'm trying to declare a const closure so I can use throughout my code:

impl<T: Default + Copy + Eq> Profiler<T> {
  pub const increase_by_one: dyn Fn(&T) = &|x| {
    *x = *x + 1;
  }
  // <...>
}

but I'm getting problems in the size not being known at compile time.

I also tried this:

impl<T: Default + Copy + Eq> Profiler<T> {
  pub const increase_by_one: fn(&T) = &|x| {
    *x = *x + 1;
  }
  // <...>
}

But it says that the type of x must be known.

Is there a way to define a closure inside a generic struct?


Solution

  • It isn't possible to define a const closure in Rust today because the type of a closure cannot be named. You could use a function pointer (fn(&T)), but that incurs call time overhead compared to a closure type. You could use a 'static trait object reference (&'static dyn Fn(&T)), but that also has call time overhead and it requires a T: 'static bound.

    Fortunately, const closures are never necessary. The only difference between a closure and a fn item is that closures can have state, but consts may not have state, so there's not really any point to combining them. Just use an associated function instead of an associated constant.

    impl<T: AddAssign<i32>> Profiler<T> {
        pub fn increase_by_one(x: &mut T) {
            *x += 1;
        }
    }
    

    See also