I understand the value of const
outside of functions because they can be inlined, but when should const
values be used within a function scope?
I was writing some code and trying to take the approach of using the most restrictive type possible (thankfully Rust has awesome defaults here), so I began to declare variable bindings as const
probably influenced by C++ background where that keyword is also used for immutablity.
But const
has the downside that types cannot be inferred, consider:
fn main() {
const NUMBERS: [i32; 5] = [1, 2, 3, 4, 5];
let numbers = [1, 2, 3, 4, 5];
const X: u32 = 5;
let x = 5;
}
After making several large arrays similar to NUMBERS
above (and wondering why the size couldn't be inferred), I asked myself the question "Why aren't I just using immutable bindings?" (like numbers
).
So I'm curious, what (if any) are the tradeoffs between function-scoped const
s compared to immutable bindings? Are there times to use one over the other? I feel it's unlikely, but can function-scoped const
's be optimized more than immutable bindings?