最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rust - Run non-const function at compile-time and use the result as if it were const - Stack Overflow

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论