What does it mean for a constant value in Rust to be inlined?
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:
- the value is simple enough: it does not even touch the stack, and instead is hardcoded directly in the assembly. This is most likely to happen for integers, for example.
- the value is not that simple: it is created in read-only memory, and referenced/copied from there. Multiple copies on the stack will have different addresses.
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.