4 ms·
Those trivial examples seem to be mostly to not scare off C++ programmers. It's more interesting, though, to see how far you can push single ownership. You can
by Animats 12y ago
Those trivial examples seem to be mostly to not scare off C++ programmers. It's more interesting, though, to see how far you can push single ownership. You can build a single-ownership tree. Rust lacks a "nil", but has discriminated variant records (called "enums") to handle has/doesn't have semantics. You can also grow a <Vec> of owning references, so you can have an array which owns a variable number of children. Using all those features together, you can build a tree. Take a look at the XML library for Rust to see how this all works.
But it can't have backpointers. That would violate single-ownership. Weak pointers for backpointers are available, but that's an unstable feature and introduces reference counting overhead. Rust needs some construct which includes a single-ownership forward pointer and a dependent back pointer, updated together so that they're always in sync.
- JoshTriplett 12y ago> Rust lacks a "nil" Rust has the concept of a possibly-null pointer; you just have to write it explicitly by wrapping something in the Option type. In particular, Rust has a guaranteed optimization that says if you have a type with a single zero-argument constructor and a one-argument constructor, and the one-argument constructor takes a type that can't be null, then the type with those two constructors will just use null to represent the zero-argument constructor. So Option on a pointer/reference type just represents a nullable pointer.
- Animats 12y agoRust's "Option" type is a generic enum. There is no explicit "nil".
- kachnuv_ocasek 12y agoThat's what she said.
- geofft 12y agoYou can always implement that sort of thing with `unsafe` blocks. Since any use of raw, non-smart pointers in C++ counts as unsafe, I think it'd be pretty okay to write a couple of helper functions to maintain that invariant, and then call those functions from safe code. But yeah, that probably ought to end up in either the standard library or a very common third-party library, at some point.
- Animats 12y agoTo do that right, you need help from the borrow checker. When manipulating an owner pointer with a backlink, you'd need the backpointer to be unborrowed at the moment the ownership changes. A feature like this needs compile time checking. I really need to think this through and make a proposal for Rust 2.