Why does `let true = false` fail, and is it really possible to do it?

Is it possible to make this work? I originally wanted to see if true could be redefined, then I saw true is actually a keyword.

Is it possible to "fix" the patterns error and get the "you-can't-assign-to-a-keyword-error"?

fn main() {
    let true = false;
}

I get:

error[E0005]: refutable pattern in local binding: `false` not covered
 --> src/main.rs:2:9
  |
2 |     let true = false;
  |         ^^^^ pattern `false` not covered

Playground

Upvotes: 1

Views: 1168

Answers (2)

Peter Hall
Peter Hall

Reputation: 58815

I'm not sure what you're trying to do or why you'd want to do it! Most people would consider it a design flaw if a language permitted you to redefine true and false and I'm sure this has been the topic of at least one installment of The Daily WTF.

Is it possible to "fix" the patterns error and get the "you-can't-assign-to-a-keyword-error"?

Constant definitions don't allow patterns, so you can get a different error by attempting to redefine true as a const:

const true: bool = false;

Which produces an error more similar to what you were after:

error: expected identifier, found keyword `true`
  --> src/main.rs:1:7 
  | 
1 | const true: bool = false;
  | ^^^^ expected identifier, found keyword 

Upvotes: 3

yorodm
yorodm

Reputation: 4461

There's nothing wrong with the error message. You're using an refutable pattern in a let binding and let only allows for irrefutable patterns.

In other words, when you do this:

let variable = value

You are not assigning a value to the variable. You're creating a binding where the left side matches something on the right side. It should be an irrefutable pattern because the match must always succeed.

Upvotes: 5

Related Questions