I recently ran into an issue where I wanted to use Any for slices. However, it only allows 'static types (based on what I read, this is because you get the same TypeId regardless of lifetimes).
I came up with this workaround which I think is safe:
It seems to pass Miri, including the mut version (which requires a bit more care to ensure there can only be one mutable reference). Any problems with doing this?
The more I think about it, the more I'm convinced the immutable slice version is safe. I'm pretty sure the mutable version in the playground is also safe because you can't turn it into a mutable reference without consuming it and it requires a mutable reference to build.
The mutable version is pretty inconvenient to actually use if you want to store the AnySliceMut and pass it to other functions. The other function would have to reconstruct it and pass it back once it was done with the mutable reference. But what if:
Thanks for the reply. Unfortunately, I could just use Any for that since Vec is 'static as long as the items are (and I don't think you could use anyvec if the tiems weren't static).
I asked in the Rust Discord channels and it seems like my approach is fine. Even the mutable version is okay and doesn't need to be unsafe if it returns the reference with self's lifetime.
I asked in the Rust Discord channels and it seems like my approach is fine. Even the mutable version is okay and doesn’t need to be unsafe if it returns the reference with self’s lifetime.
Then maybe publish it as a mini-crate (e.g. any-slice), ideally with a link to the discussion that proves that it is sound.
Note: both code fragments and links contain things like &
Yes, I know. lemmy mangles stuff like ampersand and less than even inside code blocks. I noted this in an edit for the main post and included a playground link as well.