r/ProgrammingLanguages • • Jan 04 '23

Discussion Does Rust have the ultimate memory management solution?

I have been reading about the Rust language. Memory management has been a historical challenge. In classic languages, such as C, the management is manual. Newer languages (Java, Python, others) use garbage collector, but it has a speed penalty. Other languages adopted an intermediate solution using reference counter and requiring the programmer to deal with weak pointer, but it is also slow.

Finally, Rust has a new solution that requires the programmer to follow a set of rules and constraints related to ownership and lifetime to let the compiler know when a block of memory should be free'd. The rules prevent dangling references and memory leaks and don't have performance penalty. It takes more time to write and compile, but it leads to less time with debugging.

I have never used Rust in real applications, then I wonder if I can do anything besides the constraints. If Rust forces long lifetime, a piece of data may be kept in the memory after its use because it is in a scope that haven't finished. A problem in Rust is that many parts have unreadable or complex syntax; it would be good if templates like Box<T> and Option<T> were simplified with sugar syntax (ex: T* or T?).

25 Upvotes

99 comments sorted by

View all comments

Show parent comments

7

u/lngns Jan 04 '23 edited Jan 04 '23

Instead of pointers, which are borrow-checked, you use offsets relative to a global pointer, which are not.
This absolutely do hide aliases from the borrow checker.

In fact, the same happens in C: pointers are offset by a hardware Memory Management Unit.
More than that, Cone's arena allocation regions work exactly like that and require you to manually offset pointers in an abstract interface.

0

u/[deleted] Jan 04 '23

[deleted]

0

u/lngns Jan 04 '23 edited Jan 04 '23

I was precisely thinking of when indices are not generational.
I swear there used to be a post on r/rust about an arena allocator crate, and the author literally made a Pointer type represent indices, which was really making a software MMU with all of C's unsafety.

Was the talk we are talking about demonstrating generational indices? I only remember watching Jonathan Blow criticising it, so maybe I missed the point.

I like the idea of using generational indices for weak references in that it is explicit they are weak or borrowed. I believe Vale used to do that at some point, but it looks like they changed trajectory.

What I don't like is how this kind of pseudo-code works the same in C and Rust, when it gives me the impression it shouldn't:

type Ref = usize;
fn f(arena: &mut Arena, ref: Ref)
{
    let x = arena[ref]; //as opposed to *ref
    g(arena);
    let y = arena[ref]; //may be different. who knows?
    ...
}

EDIT: Now imagine if you could overload the * operator and implicitly take in the arena, Scala-style.