nalgebra
nalgebra copied to clipboard
Improve compiler warnings with #[must_use]
Hello,
After porting my project to nalgebra, I spent way too much time debugging a black screen, which I eventually traced back to my following mistake:
view_matrix.prepend_translation(&(-camera));
This function returns a new matrix; the line is a no-op.
Enter #[must_use]:
#[inline]
#[must_use = "Did you mean to use prepend_translation_mut()?"]
pub fn prepend_translation<SB>(
...
This turns a silent error into a helpful compiler warning:
| view_matrix.prepend_translation(&(-camera));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: #[warn(unused_must_use)] on by default
= note: Did you mean to use prepend_translation_mut()?
I propose to tag all functions that return a new object without side effects as #[must_use], optionally with a hint towards an in-place alternative.
This might also help with #534.
Is this something you'd consider an improvement? Shall I try to prepare a pull request, or would you rather go through your code yourself?
Hi! This is a great idea.
Lot of nalgebra feature existed before #[must_use] was added to the language so we could not do this before. It would be a great contribution if you make a pull request for this, yes!
I saw your request for further functions on #607, @cauthmann. Since I just found a bug in my code, I'd like to propose the cap_magnitude functions. If someone (me) assumes that they would mutate their Vector/Matrix, they'd be suprised to find some unexpected behaviour.
@MalteT: That seems like a good candidate, but I don't have any active projects using nalgebra right now. Feel free to make your own PR.
Thanks! I'll see if I can find some time soon :)
Would it maybe make sense to mark the Matrix type itself with #[must_use]? I can't think of cases where it would be harmful per se, and it would be easier than marking individual functions that return Matrix.
It's such a general type, I'm not sure that's always going to be desirable, for the same reason that e.g. u32 isn't marked that way.