Cell

The Cell type stores a single data value, which we can move in and out of the Cell even if the Cell is not marked as mutable. To move a value into the Cell, we can use the following:

  • Cell::new, because the initial value was moved into the cell when the cell is created
  • set, to move a new value into the cell, and end the lifetime of the value already stored there
  • replace, to move a new value into the cell, and move the old value into the current scope

To move a value out of the Cell, we can use the following:

  • replace, to move a new value into the cell, and move the old value into the current scope
  • into_inner, to consume the cell, and return the value it contained

Cells don't support any operations that would allow us to have an empty Cell: they always have to contain something, just like the other smart pointer types.

Let's take a look at a cell in action:

let cell = Cell::new("Let me out!".to_string());
println!("{}", cell.replace("Don't put me in there.".to_string()));
println!("{}", cell.replace("I didn't do anything.".to_string()));
cell.set("You'll never hold me, copper!".to_string());
println!("{}", cell.into_inner());

Notice that the cell variable is not mutable. Here, we're setting up a cell, using replace a couple of times to retrieve the old value from the cell at the same time that we set a new one, and then using set to set a new value while discarding the old one, and finally using into_inner to get rid of the cell while extracting its contained value.

The into_inner function moves the contained value out of the cell, but that doesn't create an empty cell because the cell no longer exists. If we tried to access it after calling into_inner, we'd get an error from the compiler, as shown in the following screenshot:

There's one more function that we can use to access the data value contained in a Cell, but only if the contained data type has the Copy trait: get. We could do something like println!("{}", cell.get()) to leave the content of the cell in place while retrieving a copy of it, but only if copying the data value is actually possible.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.251.206