News for hackers. Stuff that matters.
Re:What Rust Can Do That Other Languages Can't by m1el on Monday February 06, 2017 @04:15AM (#13577836)
Let's translate this code to C++:

    class X {
      public:
        Y* getY(void) {
          return &y;
        }
      private:
        Y y;
      };
    }
`getY` returns a pointer to the struct field, this field is allocated as a part of the struct. There is no way (in C++) to verify that this pointer does not outlive the struct itself. In other words, your pointer may become stale, and the compiler has no way to check for it.

Rust has a resource ownership model (borrow checker) that allows it to check at compile time that references do not outlive the data.

Re:What Rust Can Do That Other Languages Can't by humanrebar on Monday February 06, 2017 @07:04AM (#13578665)
A little closer would be to use a shared_ptr<X> and shared_ptr<Y> that share the same reference count (1). It's not exactly the same thing, though, since Rust gives you some safe usage checks that you don't get with shared_ptr. That is, vanilla Rust objects have lifetime semantics closer to unique_ptr than shared_ptr.

(1): See constructor number 7 here, which was designed for this purpose: http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_pt...

Re:What Rust Can Do That Other Languages Can't by dbaupp on Monday February 06, 2017 @03:44PM (#13583682)
It also isn't the same in that it comes with the cost of allocation and reference counting.
Re:What Rust Can Do That Other Languages Can't by akie on Monday February 06, 2017 @04:20AM (#13577864)
Ah, I see! Thank you.
Re:What Rust Can Do That Other Languages Can't by blub on Monday February 06, 2017 @07:45AM (#13578925)
Both the original example and your translation exhibit poor API design: it's an antipattern to return mutable references to member variables. This would remove all encapsulation, which is probably the most important principle of OOP.

Nevertheless, a better solution was pointed out in an answer on the blog and by humanrebar.

Re:What Rust Can Do That Other Languages Can't by erikdesjardins on Monday February 06, 2017 @09:33AM (#13579698)
The original example does not return a mutable reference; in Rust you must explicitly opt in to mutability. Compare [1] and [2].

[1]: https://play.rust-lang.org/?gist=78e7af18c6fc7d37d9df96be63a...

[2]: https://play.rust-lang.org/?gist=2072a18b674685f20c9d1504a88...

Re:What Rust Can Do That Other Languages Can't by blub on Monday February 06, 2017 @10:48AM (#13580489)
Oh ok, my bad.

Then the C++ translation above should probably be a const& in C++, which is acceptable. The returned reference could in that case be stored, but it's risky and a bad practice.

Re:What Rust Can Do That Other Languages Can't by nallerooth on Monday February 06, 2017 @07:05AM (#13578678)
Thanks!