3 ms·
Another example: > “Use const and the compiler will optimize that away!” Nobody knows what the compiler will do, if nobody checked what the compiler did. Rust
by tialaramex 6y ago
Another example:
> “Use const and the compiler will optimize that away!” Nobody knows what the compiler will do, if nobody checked what the compiler did.
Rust (in the Rustonomicon if nowhere else) specifically promises that const gives you the same results you'd get by calculating and manually inlining the constant itself everywhere. It even spells out all the things you thus can, and can't do in a constant so that your compiler can definitely correctly evaluate the constant from the point of view of the target architecture despite potentially different hardware.
e.g. if you tell Rust
const BAR :isize = isize::from_be(0x1234);
You've conjured a constant BAR whose size and data layout depends on the target architecture, but the language promises that figuring this out incurs no runtime cost, the work will be done at compile time.
Indeed Rust will refuse to compile your program if it can't figure out how to do this, explaining what went wrong, e.g. that same above snippet would not have worked years ago, because isize::from_be() was not yet marked as suitable for such endeavours and so the compiler wouldn't attempt it.
If you mark a function the compiler can't evaluate as being suitable, the compiler will reject that too, even if you don't use the function, somebody else might and it won't disappoint them.