When you define an immutable structure in Rust, all the objects in the structure are immutable. I found out that by using types like UnsafeCell
, RefCell
, and Cell
, it is possible to make only certain objects mutable while the structure itself is immutable.
I wrote the following code, which caused an error when making the structure mutable. Since I don't want to make other parts of the structure mutable, I would like to know how I can make some objects of the mutable structure mutable.
// rust 1.51.0
// ndarray 0.14.1
pub trait Float:
num_traits::Float
+ num_traits::NumAssignOps
+ Copy
+ Send
+ Sync
+ fmt::Display
+ fmt::Debug
+ Sized
+ 'static
{}
impl<T> Float for T where
T: num::Float
+ num_traits::NumAssignOps
+ Copy
+ Send
+ Sync
+ fmt::Display
+ fmt::Debug
+ Sized
+ 'static
{}
use std::cell::UnsafeCell;
use ndarray::
struct Tensor<'a, T: Float> {
input: UnsafeCell<ndarray::Array<T, ndarray::IxDyn>;
dim: &'a [u8],
}
fn main() {
let tensor = Tensor::new();
*tensor.input.get_mut() = array;
}
error[E0596]: cannot borrow `tensor.input` as mutable, as `tensor` is not declared as mutable
--> src/tensor.rs:39:10
|
37 | let tensor = Tensor::<f32>::new(&[10,10]);
| ------ help: consider changing this to be mutable: `mut tensor`
38 | let new_array = NdArray::<f32>::ones(IxDyn(&[10,10]));
39 | *tensor.input.get_mut() = new_array;
| ^^^^^^^^^^^^ cannot borrow as mutable