Anything like Any<'a>?


#1

I’m trying to store a map of values of arbitrary types that are all valid for some lifetime 'a. The problem is 'a is not 'static, so I can’t use a cheeky Box<Any>. Is there some other way to do this in Rust? I thought if there was something like Any, but valid for some explicit lifetime instead of being static that would be good.

I’m not against an unsafe solution, but have written a grand total of 1 line of unsafe code, so am not sure how to approach it :slight_smile:


#2

Not sure if this helps, but you can do something like this: Box<&'a Any>


#3

Unfortunately that won’t work because this map is the source for these types that may not be static. The types are then lent out to other types that have the same lifetime.

When that lifetime ends they’re all dropped.


#4

I’ve started playing with *mut T for the first time and oh my god this feels so dirty, I scrub and I scrub but the stains won’t come out.


#5

hm I think there is no reason there couldn’t be an Any<'a>. The type information in an Any can’t make a difference between different lifetimes, but the Any itself could simply maintain that it has a maximal lease 'a for anything it represents.


#6

I guess the next step from that is what a Box<Any<'a>> would be. Or maybe Box<'a, Any<'a>> for heap allocated data that’s only valid for that lifetime. And then how you can get a type id for borrowed data. Personally I’m fine with the idea of just treating it as Any<'static>, as suggested here.


#7

Box can alread contain arbitrary type (including references). Maybe Box<Any + 'a> is enough? I haven’t thought this through, so don’t take my word for it being possible or sound.

Best would be to try to implement it, unfortunately even the type id intrinsic requires T: 'static. (Yes, I know lifetimes aren’t part of the type id; it would be the “Any” implementation’s role to preserve that by other means, for example by not erasing the lifetime like other types are erased, but by preserving it.)


#8

So I just had a play around with the most naive implementation possible: remove the 'static bounds from Any and the type id intrinsic.

It all Just Works, but is unfortunately a breaking change because it looks like some people rely on implicitly binding to 'static along with Any.

I’m thinking something like an AnyKind where the current Any is just AnyKind + 'static could work around that. Personally, the type id not including lifetimes seems reasonable to me, since they don’t really exist at runtime.

I might spend a bit more time playing with it and then move over to internals and see what people think.

EDIT: Started a topic on internals for allowing non-static type ids.