Is unsafe non-static `TypeId::of_unchecked()` possible?

I find myself from time to time needing Any/TypeId for non-static types when I can prove that lifetimes guaranties will be kept but compiler doesn’t know that.

The problem is that unlike with borrow-checker (where we have unsafe) or Send/Sync (manually implementable), there is no way to do the same for TypeId. There is no problem with Any in general, as it is just an implementation above TypeId, but I can’t implement any such abstraction (even if unsafe) for non-static types myself because TypeId doesn’t let me and can’t check types without it before casting.

What I’m asking is something like:

impl TypeId {
    unsafe fn of_unchecked<T: ?Sized>() -> Self
}

At least that way we will have some tools to work with when lifetimes cannot be proven by compiler similar to how we can “override” borrow checker rules. I don’t think we need a non-static Any, only a basic primitives that allow us to build our own abstractions.

Relevant discussion:

2 Likes

it is:

2 Likes

Thanks, saw this workaround in the Zulip link provided above. At least now I’m no longer blocked.

On the other hand this one really feels like I’m fighting/exploiting the language instead of using provided tools. It would be great if we can have “official“ way to do this somewhere in the future.