Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't Have Mutable reference of struct instead of &self in cost function of trait CostFunction. #545

Open
ramtinkh opened this issue Dec 9, 2024 · 3 comments

Comments

@ramtinkh
Copy link

ramtinkh commented Dec 9, 2024

I'm trying to have an element in my struct that changes during Nelder Mead optimization. But despite trait CostFunction I'm not allowed to have mutable reference &mut self in cost function.
What do you recommend me to do?

@stefan-k
Copy link
Member

stefan-k commented Jan 3, 2025

You could try interior mutability using RefCell: https://doc.rust-lang.org/book/ch15-05-interior-mutability.html

@ramtinkh
Copy link
Author

ramtinkh commented Jan 4, 2025

I used it but it didn't completely solve my error (Somewhere else another error occured).
I was wondering if there was a reason you have not used &mut self in the trait CostFunction? Or you did it just to avoid possible errors and reach a stable version ASAP?

@stefan-k
Copy link
Member

stefan-k commented Jan 5, 2025

The downsides of using &mut self overweight the advantages. Handling gets much more cumbersome and restrictive due to requiring unique ownership of the problem when evaluating the cost function. If interior mutability is needed, RefCell should to the trick.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants