
Two Beautiful Rust Programs - yannikyeo
https://matklad.github.io//2020/07/15/two-beautiful-programs.html
======
millstone
I think the first example is actually not very compelling for C++ programmers,
because it's specific to vector. e.g. in C++ this is safe:

    
    
        deque<int> xs = {1, 2, 3};
        int *x = &xs[0];
        xs.push_back(92);
        cout << *x;
    

but Rust would still reject this.

~~~
flohofwoe
But this is purely by convention isn't it? You as the programmer have to know
that deque<> never changes item locations in memory under the hood like
vector<> does, the compiler will not complain either way.

There's nothing in the interface of vector<> or deque<> that somehow hints to
the user or (more importantly) to the compiler that one randomly moves things
around in memory and the other doesn't. That's what makes C++ so extremely
memory-unsafe (IMHO it's even worse in C++ than C, because at least in C,
dynamic memory management usually is right in your face and not hidden under a
sugarcoating layer like nearly everywhere in the C++ stdlib).

~~~
millstone
Right. Iterator invalidation rules are important yet only checked indirectly,
through tools like ASAN or VC++ debug iterator support. It's a big problem.

But Rust has its conventions too. Probably you would satisfy the borrow
checker through an index instead of a pointer:

    
    
        let mut xs = vec![1, 2, 3];
        let idx = 0;
        xs.push(92);
        println!("{}", xs[idx]);
    

This is memory safe, but in an unsatisfying way. Nothing hints to the compiler
that idx is connected to the vector. If you inserted into the front rather
than the back, you would have a "dangling index". You just have to know to not
do that. It's purely by convention too, except there's no tooling support to
help.

It turns out programs really do need a way to hold references to collection
elements across mutation.

~~~
zbentley
> This is memory safe, but in an unsatisfying way.

How is it unsatisfying? I know that "xs[idx]" isn't going to be garbage data
from elsewhere in my program, and that it won't occasionally segfault when I
try to print it.

That's a big improvement.

------
doonesbury
Rust pieces should stick to problem and solutions and why rust is a better
hammer. C/c++ need some competition in the systems space. Drop the sales and
marketing puff piece approach

------
GoblinSlayer
Never understood python programmers' complaints about punctuation noise in
curly brace languages, but looking at rust I feel like I start to understand
what they mean.

