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:
new(value: T) -> Self: This constructor should create a newCellinstance initialized with the providedvalue.get(&self) -> &T: This method should return an immutable reference to the value stored within theCell.set(&mut self, value: T): This method should update the value stored within theCellwith a newvalue.
Key Requirements:
- The
Cellstruct must be generic over the typeTit holds. - The
getmethod should not allow mutation of the stored value. - The
setmethod must allow mutation of the stored value.
Expected Behavior:
- A
Cellcreated with a specific value should return that value whengetis called. - After calling
setwith a new value, subsequent calls togetshould return the newly set value.
Edge Cases to Consider:
- What happens if
Tis a type that implementsCopy? - What happens if
Tis a type that does not implementCopy(e.g.,String)? Thesetmethod 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
Tcan be any type that Rust supports (primitive types, structs, enums, etc.). - The
Cellstruct should be implemented within a single Rust file. - No external crates are allowed for the core
Cellimplementation.
Notes
- Consider how Rust's ownership and borrowing rules apply to the
getandsetmethods. - Think about the differences between mutable and immutable references.
- The
setmethod will need to consume the old value and replace it with the new one.