Hone logo
Hone
Problems

Rust Cell: Implementing a Basic Memory Cell

This challenge involves creating a fundamental data structure in Rust: a "Cell". A Cell will act as a container for a single value and should provide methods to get and set that value. This is a building block for more complex data management and is analogous to simple memory locations or observable data holders.

Problem Description

Your task is to implement a generic Cell<T> struct in Rust. This struct should be capable of holding a value of any type T. You need to provide two primary methods:

  1. new(value: T) -> Self: This constructor should create a new Cell instance initialized with the provided value.
  2. get(&self) -> &T: This method should return an immutable reference to the value stored within the Cell.
  3. set(&mut self, value: T): This method should update the value stored within the Cell with a new value.

Key Requirements:

  • The Cell struct must be generic over the type T it holds.
  • The get method should not allow mutation of the stored value.
  • The set method must allow mutation of the stored value.

Expected Behavior:

  • A Cell created with a specific value should return that value when get is called.
  • After calling set with a new value, subsequent calls to get should return the newly set value.

Edge Cases to Consider:

  • What happens if T is a type that implements Copy?
  • What happens if T is a type that does not implement Copy (e.g., String)? The set method should handle ownership transfer correctly.

Examples

Example 1:

Input:
let mut my_cell = Cell::new(10);
println!("Initial value: {}", my_cell.get());
my_cell.set(20);
println!("New value: {}", my_cell.get());

Output:

Initial value: 10
New value: 20

Explanation: A Cell is created with the integer 10. get returns 10. set updates the internal value to 20. A subsequent get returns 20.

Example 2:

Input:
let mut string_cell = Cell::new(String::from("hello"));
println!("Initial string: {}", string_cell.get());
string_cell.set(String::from("world"));
println!("New string: {}", string_cell.get());

Output:

Initial string: hello
New string: world

Explanation: A Cell is created holding a String. The set method correctly handles the ownership transfer of the new String.

Constraints

  • The type T can be any type that Rust supports (primitive types, structs, enums, etc.).
  • The Cell struct should be implemented within a single Rust file.
  • No external crates are allowed for the core Cell implementation.

Notes

  • Consider how Rust's ownership and borrowing rules apply to the get and set methods.
  • Think about the differences between mutable and immutable references.
  • The set method will need to consume the old value and replace it with the new one.
Loading editor...
rust