Mutating an Rc with Rc::get_mut

In the book chapter on Rc, it doesn't mention that it IS possible to mutate an Rc, if (dynamically) the reference count is 1. I only just discovered this.

So, for example if you want to concatenate two Rc strings, you can use Rc::get_mut to append to the existing value if possible, or "start from scratch" if it's not possible ( the first string is actually shared ).

For a long time I believed that an Rc simply could not be mutated, so this was a bit of a revelation for me. Are there any other clever Rust features you might not know about after reading "the book"?

It's related to unsafe Rust, so a bit advanced, but I was quite surprised about what Rc::into_raw can do: it provides a pointer to the inner value.

Yet Rc::from_raw can be used to restore the Rc, because the extra data from the Rc is still in memory (before the inner value).

It's not really a "rust feature", it's a feature of the Rc type. And yes, there are lots of (most really) things not talked about in the book. (just as an example, most of the iterator API isn't in the book)

After reading the book, you should have a good grasp of the language. Not a complete knowledge of the standard library.

2 Likes

By "Rust" I mean loosely the language and the standard library (std).

There's lots of stuff not in the book. Here's another: Temporarily opt-in to shared mutation – Alice Ryhl

1 Like

The Book is not a comprehensive, detailed reference manual. It is an introductory turorial. You will encounter many (and I mean many) other clever techniques by browsing the std documentation (for that, visit std - Rust) and by reading lots of real-life code written by experienced Rust programmers.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.