Constant functions

The const_fn feature enables you to declare some functions as constant so that they can receive constant arguments at compile time and be executed then instead of at runtime. This is particularly useful for constructors or for constants that need to create an object as soon as possible.

For this last option, we have the lazy_static!{} macro, as we will see in the next chapter, but this macro runs all of its code at its first use, and not at compile time. Doing it at compile time would make compilations take a bit longer, but when running, it would not require computing anything as everything would already be a constant. It seems that not all lazy_static!{} cases can be solved with const_fn, though.

Let's see what it looks ...

Get Rust High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.