Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean for a constant value in Rust to be inlined?

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?

like image 935
Chakravarthy Raghunandan Avatar asked Oct 20 '16 07:10

Chakravarthy Raghunandan


2 Answers

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.

like image 131
Matthieu M. Avatar answered Sep 18 '22 03:09

Matthieu M.


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.

like image 36
WiSaGaN Avatar answered Sep 21 '22 03:09

WiSaGaN