How to modify non-mutable struct?

Of course I know this is not possible in rust .... but what are my other choices?

I have a struct MND that evaluates a MultiNormal Distribution:

MND::evaluate(&self, x: &Vec<f64>)

This requires a few algebraic operations (matrix multiplication etc.) so I need some scratch memory to keep intermediate values. Since both a function argument x and a self reference are const, I'm allocating a temporary matrix inside the MND::evaluate(). This however turned out to be a serious efficiency issue and I have to refactor the code. The easiest solution would be to store scratch matrix as a private field in an object and change the signature to

MND::evaluate(&mut self, x: &Vec<f64>).

This however causes problems somewhere else; it would be much better to keep &self immutable during this call. So what are my other options?

In C++, I'd try a global variable inside the very .cc file or const_cast

Sounds like you could solve this with interior mutability? I.e. store your scratch memory in a RefCell (or Mutex if you need thread-safety).

2 Likes

Thanks!

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.