This is a kind of stupid example, but imagine you have to implement some external trait (e.g. in order to work with some dependency) with the following shape:
trait Foo {
fn foo(&self, i: usize) -> &Bar;
}
Which is not too unreasonable, for example it’s very similar to the stdlib’s Index
. In order to implement this trait you must return a reference, you can’t return e.g. a Cow
or an Arc
. The fact that it takes a parameter means there might not even be one single value it has to return, so you can’t even cache that inside of self
with e.g. LazyLock
.
Of course I’m not saying I would try to reach for an escape hatch if I had to do something like this. I would first try to see if this is an intrinsic problem in my code, or if maybe I can change the crate I’m working with to be more permissible. That is, I would try to look for proper solutions first, though Cow
might not always work for that.
So there is no general escape hatch.
I’m not arguing that it is easier to code in C# than in Rust, just that this particular escape hatch is possible in C# and not in Rust. It’s just an observation.
It does not really matter, but does it have to?