You are viewing a single thread.
View all comments
19 points

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.

permalink
report
reply
7 points

(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.

permalink
report
parent
reply
4 points
  1. Unconvincing use-case: why is returning an Option not an option?
  2. Unconvincing objection: what concrete problems are caused by utilizing Cows?
  3. Wrong demonstrated “solution”: why would one have to create a value and leak it with each call instead of using one LazyLock static?
permalink
report
parent
reply
1 point

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 like static, 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.

permalink
report
parent
reply

Rust

!rust@programming.dev

Create post

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

Credits
  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

Community stats

  • 605

    Monthly active users

  • 885

    Posts

  • 3.8K

    Comments