The documentation for const
:
Constants live for the entire lifetime of a program. More specifically, constants in Rust have no fixed address in memory. This is because they’re effectively inlined to each place that they’re used. References to the same constant are not necessarily guaranteed to refer to the same memory address for this reason.
I've only seen "inline functions" in C++, but never inline constant values. What is a beginner friendly explanation of how this works?
I'm also confused by "no fixed address in memory". Does that mean every time we use a const
value, a value on the stack is allocated just for this expression and after the expression is done executing, it'll be destroyed?
I've only seen "inline functions" in C++, but never inline constant values.
The closest approximate to a const
in Rust is an enum
in C++.
What is a beginner friendly explanation of how this works?
The simple beginner's explanation is: it just works, don't worry about the nitty-gritty details.
I'm also confused by "no fixed address in memory". Does that mean every time we use a
const
value, a value on the stack is allocated just for this expression and after the expression is done executing, it'll be destroyed?
Yes. Maybe. No.
It means exactly what it says on the tin: no guarantee is made. This leaves the compiler with the maximum freedom to optimize things.
Alright, that's all good and well, but... what really happens?
In practice, there are two situations:
What does simple mean? Well, it depends. For each call site the compiler may decide "simple enough" or not, which is where it is close to inlining.
Does that mean every time we use a
const
value, a value on the stack is allocated just for this expression and after the expression is done executing, it'll be destroyed?
It will not be destroyed. const
variables cannot have a type that implements Drop
. The value is just forgotten when it is no longer used. If it ever occupied memory on the stack, this memory will be overwritten sometime later.
const N: i32 = 5
in Rust is like #define N 5
in C or C++ done with type-safety.
You can think of it like a textual substitution when the type matches, that is, let foo = 32 + N;
is equivalent to let foo = 32 + 5;
in your example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With