4 ms·
I have been paying attention to Rust for the past year or so and I think it'll be the next language I will end up learning. I do have a question: what is const
by tiniuclx 8y ago
I have been paying attention to Rust for the past year or so and I think it'll be the next language I will end up learning. I do have a question: what is const fn supposed to be used for? Is it for denoting pure functions? That would be really nice, considering that not many non-functional languages explicitly recognise pure functions.
- steveklabnik 8y agoconst fn is used for compile-time programming. "pure" is a bit over-loaded of a term, but you can sort of think of it that way, sure. You can of course also run these functions at runtime; they're a more restricted kind of function. You cannot even currently use if inside of them, for example. We're working on expanding it out, but we're going slow because it's important for soundness reasons.
- lultimouomo 8y agoShould we think of them like the equivalent of constexpr functions in C++?
- steveklabnik 8y agoI am not familiar enough to declare an equivalence, but roughly the same, yes.
- tux3 8y agoYes, but hopefully without the amusing issue of non-constant constexpr functions in C++ :) http://b.atch.se/posts/non-constant-constant-expressions/ http://b.atch.se/posts/non-constant-constant-expressions/
- PowerGuido87 8y agoSo they're more like C++20's consteval? http://wg21.link/p1073r3 http://wg21.link/p1073r3
- tux3 8y agoAs I understand it, not really no. The conceptual difference between constexpr and consteval is that consteval is guaranteed to be evaluated at compile-time, so unlike constexpr code, consteval code will never actually end up as a function in your binary. Rust's const fns on the other hand can be called at runtime, so in that respect they'd be closer to constexpr.
- tiniuclx 8y agoAh thank you, that makes a lot of sense! It's good that this sort of stuff can be made explicit... a lot of C++ compile-time evaluation optimisations feel like magic to me.
- deleted 8y ago[deleted]
- KevinEldon 8y agoWhen a const fn is called from a const context, like assigning a value to a constant, the compiler interprets the function at compile time. If you're interested in more info the docs [1] and the New Rustacean 1.31 Part 2 podcast [2] are helpful. [1] https://github.com/rust-lang-nursery/reference/blob/master/src/items/functions.md#const-functions https://github.com/rust-lang-nursery/reference/blob/master/s... [2] https://newrustacean.com/show_notes/news/rust_1_31/part_2/index.html https://newrustacean.com/show_notes/news/rust_1_31/part_2/in...