Cool, that was an informative read!
If we were willing to leak memory, then we could write […]
Box::leak(Box::new(0))
In this example, you could have just made a constant with value
0
and returned a reference to that. It would also have a'static
lifetime and there would be no leaking.Why does nobody seem to be talking about this?
My guess is that the overlap in use cases between Rust and C# isn’t very large. Many places where Rust is making inroads (kernel and low-level libraries) are places where C# would be automatically disqualified because of the requirements for a runtime and garbage collection.
(Note that I’m not the article author)
In this example, you could have just made a constant with value
0
and returned a reference to that. It would also have a'static
lifetime and there would be no leaking.I believe the intention was to demonstrate something that works with runtime values too, and a constant 0 does not.
Btw you can just write
&0
to do what you proposed, there’s no need for an explicit constant/static.- Unconvincing use-case: why is returning an
Option
not an option? - Unconvincing objection: what concrete problems are caused by utilizing
Cow
s? - Wrong demonstrated “solution”: why would one have to create a value and leak it with each call instead of using one
LazyLock
static?
I can agree that the example function is not the best usecase. But the point still stand that there’s no realistic escape hatch from lifetimes and memory management in Rust.
Cow
does not work when you are actually required to return a reference, e.g. if you’re working with some other crate that requires that.Cow
also has some more strict requirements on reborrows (i.e. you can reborrow a&'short &'long T
to a&'long T
, but you can only reborrow a&'short Cow<'long, T>
to a&'short T
).LazyLock
can solve very specific issues likestatic
, but is not a general escape hatch. Again, the example is not the best to showcase this, but imagine if you have to perform this operation for an unknown amount of runtime values.LazyLock
will only work for the very first one.Cow
does not work when you are actually required to return a referenceWhat does that even mean? Can you provide a practical example?
(I’m assuming you’re familiar with
Deref
and autoref/autoderef behaviors in Rust.)
- Unconvincing use-case: why is returning an