Transforming Non-Cloneable Types into Cloneable Values
Reference-Counted Values and Interior Mutability
If your type is not cloneable, you can transform it into a reference-counted value such as Rc
or Arc
, which can then be cloned. You may or may not also need to use interior mutability.
Interior Mutability
Interior mutability allows you to mutate a field of a struct while it is borrowed. This is useful when you need to modify the state of an object without taking ownership of it.
The Mutex
and RefCell
types are two common ways to achieve interior mutability. Mutex
provides mutual exclusion, while RefCell
is non-blocking.
Example
struct Foo { a: Vec, b: i32, } let mut foo = Foo { a: vec![1, 2, 3], b: 4 }; // Borrow foo's vec let a = &mut foo.a; // Modify the vec a.push(4); // Now we can mutate foo's b field foo.b = 5;
In this example, we have a struct Foo
with two fields: a mutable Vec
and an immutable i32
. We borrow the Vec
and modify it, which is allowed because we have interior mutability. We can then mutate the i32
field without any problems.
Komentar