Search code examples
rustconstantslet

Can I shadow a const binding with a local variable?


I thought this would work:

const x: &str = "10";            // declare a const
let x: i32 = x.parse().unwrap(); // reuse the same name for a let binding
assert_eq!(10, x);

But:

error[E0308]: mismatched types
 --> src/main.rs:3:9
  |
3 |     let x: i32 = x.parse().unwrap(); // reuse the same name for a let binding
  |         ^ expected i32, found reference
  |
  = note: expected type `i32`
             found type `&'static str`

error[E0277]: the trait bound `{integer}: std::cmp::PartialEq<&str>` is not satisfied
 --> src/main.rs:4:5
  |
4 |     assert_eq!(10, x);
  |     ^^^^^^^^^^^^^^^^^^ can't compare `{integer}` with `&str`
  |
  = help: the trait `std::cmp::PartialEq<&str>` is not implemented for `{integer}`
  = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

This works:

const x: &str = "10";
let y: i32 = x.parse().unwrap();
assert_eq!(10, y);

And so does this:

let x: &str = "10";
let x: i32 = x.parse().unwrap();
assert_eq!(10, x);

Am I doing something wrong, or is it not possible to shadow an existing const binding with a let under the same name?


Solution

  • I think I get it... when I use let SOME_CONST, the compiler thinks I'm pattern matching.

    When I fix the types:

    const x: i32 = 10;
    let x: i32 = x + 1;
    assert_eq!(11, x);
    

    I get a different error:

    error[E0005]: refutable pattern in local binding: `_` not covered
     --> src/main.rs:3:9
      |
    3 |     let x: i32 = x + 1;
      |         ^ interpreted as a constant pattern, not new variable
    

    As if I had taken all occurrences of x in the program and expanded them to the constant 10:

    let 10: i32 = 10 + 1;
    assert_eq!(11, x);