1

I'd like to create a struct that can hold on to a bunch of closures for me to later use them. The closures should also have the Clone trait on them too.

What's the syntax for declaring that?

My attempt which doesn't compile:

pub struct Equations {
    eqns:Vec<impl Fn(f32) -> f32 + Clone>,
}

And another attempt, I can't quite get the required syntax here (or how to look it up).

trait AnonFunction: Fn(f32) -> f32 + Clone {}

pub struct Equations {
    eqns:Vec<dyn AnonFunction>,
}

Edit: Not sure why this was voted to be closed, I was linked to this question: How to represent an opaque type in a struct field which requires an understanding of async, macros, potentially the genawaiter crate just to understand what is being asked. And is a much longer question.

I think the question herein is simpler as it is only talking specifically about anonymous closures which suits the Q&A style format. I did go to the effort of making a simpler example, not just copying the code verbatim from my main project.

dim_voly
  • 478
  • 2
  • 10
  • 20
  • You should add the full compiler error message(s). – cafce25 Feb 27 '23 at 21:42
  • We might be getting somewhere with `pub struct Equations {eqns:Vec f32>>}`. But I still can't get `Clone` to work. If I add `Clone` via a supertrait, it complains of `this trait cannot be made into an object... ..because it requires 'Self: Sized'`. – dim_voly Feb 27 '23 at 21:55
  • 1
    Well it's either a trait object, or a generic. Not sure why you need `Clone` anyways since `&Fn()` also implements `Fn()` – cafce25 Feb 27 '23 at 22:02
  • Thanks. I can try without `Clone`, I've had issues when I `move` the equations it wanted `Clone` implemented. – dim_voly Feb 27 '23 at 22:04

0 Answers0