0

I want to create a structure that has a field mut_f that contains mutable thread safe function(closure) that type is A -> A

For the initialization, the value is identity closure.

let identity = |a| a;

struct Foo<A> {
    mut_f: Arc<Mutex<dyn FnOnce(A) -> A>> 
}

let foo = Foo {
    mut_f: identity //error
};

This obviously has the error:

let identity = |a| a; mismatched types

expected struct std::sync::Arc, found closure

note: expected struct std::sync::Arc<std::sync::Mutex<(dyn std::ops::FnOnce(_) -> _ + 'static)>> found closure [closure@src/main.rs:36:20: 36:25] help: use parentheses to call this closure: (a)rustc(E0308) main.rs(36, 20): the found closure main.rs(44, 17): expected struct std::sync::Arc, found closure No quick fixes available

and basically, I want to keep the closure definition as simple as possible because later I need to compose another functions(closures) in function composition manner.

So my question is what is the adequate/smart way to Cast closures to the Arc<Mutex<dyn FnOnce(A) -> A>> type?

KenSmooth
  • 275
  • 1
  • 10
  • 2
    Does https://stackoverflow.com/questions/27831944/how-do-i-store-a-closure-in-a-struct-in-rust answer your question? (the accepted answer has an example of a boxed closure) – lkolbly Jan 21 '22 at 22:07
  • Actually yes and I've seen the answer, but did not noticed `Arc::new(Mutex::new(identity))` is the exact answer, so if you post the answer, I will accept that. The credit is yours. Thanks! – KenSmooth Jan 21 '22 at 22:28

1 Answers1

2

The Foo is expecting a Arc<Mutex<dyn FnOnce>>, so if you pass just a closure you'll get that error. You can get around that by constructing the Arc and Mutex:

let foo = Foo {
    mut_f: Arc::new(Mutex::new(identity))
};
lkolbly
  • 1,140
  • 2
  • 6