308. sin_cos — One Angle, Both Halves, No Swap Bug
Every rotation, polar conversion, and circle you draw needs sin and cos of the same angle — and every codebase has one spot where x got the sin and y got the cos.
Two separate calls means two chances to put the results in the wrong slot, and the compiler can’t help — both are f64. sin_cos returns the pair as a tuple, so the destructure names them once and the math below reads like math:
| |
One thing to burn in: the tuple is (sin, cos) — sin first, matching the method name, even though (x, y) order would put cos first. Destructure as let (s, c) = … and the names keep you honest.
The classic customer is a 2D rotation, where the same sin and cos appear four times:
| |
Without sin_cos that function either calls sin and cos twice each, or you write the two temporaries by hand — which is exactly where the swap sneaks in.
Don’t reach for it as a speed hack: std is free to implement it as the two calls you’d have written, and often does. The win is intent — one angle in, both halves out, and bite 300’s atan2 will happily turn the pair back into the angle:
| |
If a sin and a cos of the same angle sit within three lines of each other, they want to be one sin_cos.