Car Wheel example in shared ownership section of rust book

This is also works. so why have to use Rc?

struct Car {
    name: String,
}

struct Wheel<'a> {
    size: i32,
    owner: &'a Car,
}

fn main() {
    let car = Car { name: "DeLorean".to_string() };

    for _ in 0..4 {
        Wheel { size: 360, owner: &car };
    }
}

Thanks.

1 Like

It would be helpful if you provided a link to the part of the book in question.

It's a trivialised example; you don't have to use Rc. It's being used here because the topic is ownership; Rc gives you shared ownership. & only gives you a shared borrow.

Think about the difference between owning a house and renting one.

I'm sure it would be welcome if we can make an even better example. Examples need to be simple, clear, preferably only introduce one new thing, and seem motivated. So let's see if we can invent something better here.

2 Likes

As a rust newbie, my initial impression was that this example wasn't possible without Rc in Rust, so that's why it was used as the example. This part could be improved to show that this can be done without an Rc type, while providing another example for where Rc would be necessary.

I think the Book wants to explain some resources, like Box, Rc, Arc etc, in that section (about ownership). The lifetime and references are explained in another part of the book.

I meet this problem again. Still do not know when to borrow and when to Arc or Rc.

If I can achieve the goal with one of them, why bother to use another? There must be a problem can be solved by one, but not another.

Here are some positives and negatives with each method:

  • &'a T No runtime overhead, but limited by the lifetime 'a and thereby by a scope.
  • Rc<T> Can move out of scopes, but comes with a runtime overhead and cannot be shared between threads.
  • Arc<T> Same as Rc<T>, but with an atomic counter (a little more expensive, IIUIC). The atomic counter make it possible to share it between threads, but only if T is Send + Sync.

The content of Arc<T> and Rc<T> is also always immutable, unless T has some inner mutability mechanism. I hope this helped.

6 Likes

Thanks. I think this is the best explanation about these concepts.