0

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
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
musako
  • 897
  • 2
  • 10
  • 26
  • Your question might be answered by [Need holistic explanation about Rust's cell and reference counted types](https://stackoverflow.com/q/45674479/155423). – Shepmaster May 03 '21 at 14:14
  • 1
    It's hard to answer your question because it doesn't include a [MRE]. The code provided is not syntactically valid. It would make it easier for us to help you if you try to reproduce your error on the [Rust Playground](https://play.rust-lang.org) if possible, otherwise in a brand new Cargo project, then [edit] your question to include the additional info. There are [Rust-specific MRE tips](//stackoverflow.com/tags/rust/info) you can use to reduce your original code for posting here. Thanks! – Shepmaster May 03 '21 at 14:15
  • You can't call a method that requires a `&mut self` if you don't have a mutable value. https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#method.get – Shepmaster May 03 '21 at 14:17

0 Answers0