What does it mean for a constant value in Rust to be inlined?
constants, inline, rust
Solution
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.
Problem
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?