If you are worried about
Obj.magic
being implemented in a future version of Ocaml asassert false
instead of identity, it is trivial to implement your own identity casting function which relies on nothing but Ocaml’s C FFI. (However that would I suspect be a pointless worry: as you yourself have recognised, it is the risk of Ocaml changing its representation of Ocaml entities in memory which is going to get you.)
I think that is unrealistic to assume a language without a casting identity.
From a practical standpoint, there are many cases where the programmer might need an escape hatch and, if they know how to properly abstract their interface, it can be done safely.
One case I worked on recently involved mixing extensible variant types and value marshalling (another casting identity albeit a costly one!).
Since those two do not work together, we ended up re-working it using Obj.magic
over pairs of the form (<name>, <value>)
.
When properly abstracted with a mli
, it works and functionally achieves the same as extensible variant types.
There are many things to discuss in terms of optimizations and etc. but, from a practical programmer’s perspective, if you are ok with the trade-offs made here, I believe that it is a very valid use of the language.
Which bears the question: is there a recommended type casting identity in the official API?