问题描述
在 Rust 中定义不可变结构时,该结构中的所有对象都是不可变的。我发现通过使用 UnsafeCell
、RefCell
和 Cell
等类型,可以仅使某些对象可变,而结构本身是不可变的。
我写了下面的代码,导致在使结构可变时出错。由于我不想使结构的其他部分可变,我想知道如何使可变结构的某些对象可变。
// 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
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)