How is const array embedded?

As regards const, pust the docs state (emphasis mine):

Constants live throughout the entire program life cycle. More specifically, constants in Rust do not have a fixed address in memory. This is because theyre effectively attached to every place in which they are used . For this reason, references to the same constant do not necessarily guarantee access to the same memory address.

So, I wonder how the array of constants is "effectively embedded." See my comments in the following snippet:

const ARR: [i32; 4] = [10, 20, 30, 40];

fn main() {
    // is this 
    println!("{}", ARR[1]);

    // the same as this?
    println!("{}", [10, 20, 30, 40][1]);

    // or this?
    println!("{}", 20);
}

I appreciate any clarification!

+4
source share
1 answer

. - " , ". :

const ARR: [i32; 4] = [10, 20, 30, 40];

#[inline(never)] fn show(v: i32) { println!("{}", v); }

fn main() {
    // is this 
    show(ARR[1]);

    // the same as this?
    show([10, 20, 30, 40][1]);

    // or this?
    show(20);
}

, LLVM IR , main:

define internal void @_ZN4main20hf87c9a461739c547ZaaE() unnamed_addr #4 {
entry-block:
  call void @_ZN4show20h659b6b1f4f7103c4naaE(i32 20)
  call void @_ZN4show20h659b6b1f4f7103c4naaE(i32 20)
  call void @_ZN4show20h659b6b1f4f7103c4naaE(i32 20)
  ret void
}

show, 20. !

, , show . , "inlined" , ; . - Rust, , .

+6

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


All Articles