What does it mean that a constant value in Rust needs to be embedded?

Documentation forconst :

Constants live throughout the life of the program. In particular, constants in Rust do not have a fixed address in memory. This is because they are effectively attached to every place they use. For this reason, references to the same constant do not have to refer to the same memory address.

I only saw "built-in functions" in C ++, but never included constant values. What is a friendly explanation for beginners, how does it work?

I am also confused by "no fixed address in memory". Does this mean that every time we use a value const, the value on the stack is allocated only for this expression, and after the expression is executed, it will be destroyed?

+5
source share
3 answers

I only saw "built-in functions" in C ++, but never included constant values.

The closest approximation to constRust is enumin C ++.

What is a friendly explanation for beginners, how does it work?

Newbie’s simple explanation: it just works, don’t worry about the smallest details.

I am also confused by "no fixed address in memory". Does this mean that every time we use a value const, the value on the stack is allocated only for this expression, and after the expression is executed, it will be destroyed?

Yes. May be. No.

, : . .


, , ... ?

:

  • : , . , .
  • : / . .

? . , " " , .

, , const, , , , ?

. const , Drop. , . - , .

+6

const N: i32 = 5 Rust #define N 5 C ++, .

, , let foo = 32 + N; let foo = 32 + 5; .

+2

A const ant ; , .

MIR, :

fn main() {
    const N: i32 = 5;
}

fn main() {
    let n: i32 = 5;
}

, N , :

const main::N: i32 = {
    let mut _0: i32;                     // return pointer

    bb0: {
        _0 = const 5i32;                 // scope 0 at <anon>:2:20: 2:21
        return;                          // scope 0 at <anon>:2:5: 2:22
    }
}

, .

: , , MIR. , ( ) LLVM ASM. , .

+1
source

Source: https://habr.com/ru/post/1658292/


All Articles