[][src]Module show_notes::e015

Not dumb pointers.


This episode, we take a close look at smart pointer types---from a few we've already talked about, like Box, Vec, and String, to some new ones, like Rc and Arc.

Note: The examples below are in-progress: the Rc example is complete but not fully documented, and there's no examples yet for Arc---but there will be! I expect to finish them over the course of this weekend, but I wanted to go ahead and get the episode out!

Further reading


(Thanks to the couple people donating who opted out of the reward tier, as well. You know who you are!)

Become a sponsor



The most basic examples of smart pointers involve the Box type, which we've talked about before. Assume we had a type Foo which took a string in its constructor, and that we wanted to box it up. We would just write:

This example is not tested
let someFoo = Box::new(Foo::new("bar"));

It's also worth comparing the Rust code above with similar code in C++. Assume we have a class with the same name; using a smart pointer (in this case, unique_ptr, returned from make_unique) would give us this code:

const auto someFoo = std::make_unique<const Foo>("bar");

Both examples declare a smart pointer named someFoo that points to an immutable/constant Foo and where the pointer itself is immutable/constant. However, note that the Rust code is briefer and (at least in my opinion) substantially clearer than the corresponding C++ code to express the same semantic content.

I'm not including further comments on Box here in the docs, because we've covered it before and it's fairly straightforward. The rest of these materials focus entirely on Rc and Arc, as those are the most interesting bits from today's episode.



A trivial (and frankly rather silly) example for use with Rc.



Demonstrate the basics of reference-counted types. (Read the source, Luke!)


Note that this takes ownership of the data.


Note that this function is not generic because it assumes FileData.


Note that this function is generic: it will work for any type.