Storing arbitrary Fn in Any


#1

I have an Any and I’d like to put Fn(&mut Cow<str>) in it. How can I do this?


#2

You need to give more information thann that, how are you storing your Any and Fn?


#3

let my_any: Any = my_fn.into();?


#4

Any is unsized so this isn’t possible to use it on the stack directly, same with FnMut.


#5

True, I wrote it to quickly. My point was, that if you have FnMut, you simply into it into Any.


#6

But you can’t because that would require an impl of Into<dyn Any> for dyn FnMut, which doesn’t exist


#7

I have:

type Handlers<T> = Arc<Vec<RwLock<Deeply<Nested<dyn for<'a> Fn(&'a mut T)>>>>>;
type HandlerHolder = AnyMap;

and I would like to put a Handlers<Cow<str>> in the AnyMap.


#8

He never told, he have dyn FnMut, I understand him, that he has some actuall function (probably closure, but thats only guess), so it would be some unspecified type, which is impl FnMut. But this actually requires clarification.


#9

I’m a they


#10

Ah, ok


#11

Could you please post the actual type.


#12

sorry I got it slightly wrong: https://cybre.tech/SoniEx2/rust.eventbus/src/branch/master/src/lib.rs#L206


#13

Shouldn’t the RwLock be inside of the Arc, otherwise there is no reason to have it.

struct Handlers<T: Event + ?Sized>(Vec<Arc<RwLock<(i32, Arc<dyn Fn(&mut T) + Send + Sync>)>>>);

#14

I can assure you that this is correct.


#15

How does that work. The outer RwLock adds zero value, and actively makes it harder to read and write code.


#16

The point is that you can clone the Arc and make_mut the original. It doesn’t lock the whole thing just to modify the innermost elements.


#17

I don’t think you can convert trait objects to other trait objects, because there is no way guarantee to know how to construct the fat pointer. For example,

&dyn Debug cannot be converted to &dyn Any, because you can’t recover the pointers to the functions in Any from a reference to Debug. The conversions that Any does are special cased.


#19

what about Arc? what about Vec<Arc>? I think the problem of turning &dyn Foo into &dyn Any is that it isn’t 'static, not the vtable.


#20

Is this a problem for you to store Arc<dyn Fn(&mut T)>> in your AnyMap ? It is 'static , so it shouldn’t be a problem.


#21

I want T to be something like Foo<'a>.