In rust, the const fn
makes it possible for the compiler to compute the return value at compile-time. But sometimes the function is from a library not under my control, and I know it will always return the same result for the same parameters. (That is, if it does not do that anymore in the future, it is a breaking change that violates my usage anyway).
Is there a macro, or another way, to call the non-const function in a const context?
I am imagining a macro that executes some non-const code at compile-time and stores it in a const variable.
Example
For example, the bevy_math::primitives::dim2::RegularPolygon
has a non-const function .vertices(rotation)
. Using it would be more readable than hardcoding the vertices as literals. But I would like my function to be const:
const fn my_vertices() -> Vec<Vec2> {
let poly = RegularPolygon::new(7.0, 6);
// `vertices()` is not const, so this won't build.
let points = poly.vertices(0.0).into_iter().collect::<Vec<_>>();
points
}
This example is not justifying why I need it to be const. To be honest, it would work fine without const in my real use-case too, I doubt I'd notice a performance difference. But I would like to know this in general, out of curiosity.