5

With regards to const, the rust docs state (emphasis mine):

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.

So, I'm wondering how a const array is "effectively inlined." 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!

1 Answer 1

7

That depends. The answer is "all of the above, probably." Let's modify your example a little:

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);
}

Now, let's compile this down to LLVM IR and see what the main function looks like:

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
}

Three identical calls to the show function, each passing a constant 20. This isn't even with optimisations enabled!

In terms of what the language guarantees, the first two calls to show are semantically identical. Saying that a constant is "inlined" doesn't mean it automatically causes everything around it to be inlined, too; it just causes the value to be substituted in place. However, due to Rust's aggressive constant folding and inlining, all three are equivalent in practice, in this specific case.

Sign up to request clarification or add additional context in comments.

2 Comments

Great answer, and much appreciated. Just to reiterate you answer -- A const array is inlined (substituted in-place) like any other const, but rust will naturally optimize an indexed array literal by substituting it with the indexed value? And although the latter optimization occurs, it's not formally defined as part of the spec?
@w.brian: I think the safest thing to say is that it can optimise it. Like most optimisations, they might not happen for any number of reasons. It's possible that it's just so trivial to do that LLVM does it even at very low optimisation levels. But it might not; as far as I know, it's not guaranteed by the language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.