admin管理员组文章数量:1310160
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.
本文标签: rustRun nonconst function at compiletime and use the result as if it were constStack Overflow
版权声明:本文标题:rust - Run non-const function at compile-time and use the result as if it were const - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741849188a2400959.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论