-1

Why can't Rust use non-const-qualified functions to allocate const variables? In other words, why does it matter whether or not a function is const if the data it's operating on is const?

These questions were originally asked as part of this question, but a commenter pointed out that they would be more suitable for a separate post.

Edit: A kind user already answered these questions on my original post. Thanks @drewtato!

Edit 2: I don't get this site. Somebody complains that I have two questions in one post, so I pull one of the questions out, and then someone else complains that I pulled the question out. I try so hard to be polite and organize things the way people want, but I invariably get it wrong somehow. This isn't a duplicate. This is me pulling one of the two questions out of my original post, but referring back to the kind user that answered both of my questions instead of pedantically berating me over the finer points of SO etiquette.

mcmuffin6o
  • 348
  • 1
  • 9

1 Answers1

0

const in Rust doesn't mean "immutable" like in C for example. Const-ness is not associated with immutability, but with value being computed at the compile time.

To create such value you must be able to evaluate function at compile time, but this has many restrictions.

Aleksander Krauze
  • 3,115
  • 7
  • 18
  • Good clarification for those unfamiliar with Rust's concept of `const`. The goal of the original question was to be able to create a value at compile time. My question was that if a function is essentially a set of instructions that operates on data, then why can that set of instructions operate on data that is defined at compile time to create new data? – mcmuffin6o Aug 13 '23 at 20:31
  • @mcmuffin6o I don't get your last question. Are you asking why it is possible to create a function that is evaluated at compile time? Or why sometimes it is impossible (that is why not all functions can be `const`)? – Aleksander Krauze Aug 13 '23 at 20:42
  • 1
    @mcmuffin6o Because not all instructions can be executed at compile time; for example memory allocation can't be done at compile time. That's why everything related to memory allocation isn't and won't ever be const. Marking a method `const` essentially just means that no such instructions exists in the function, and it's evaluatable at compile time. This doesn't in any way relate to whether or not the output value is `const`, there can be instructions in the function that are not evaluatable at compile time even if the output value is `const`. – Finomnis Aug 14 '23 at 05:36