为什么 let true = false 会失败,真的可行吗?

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

有可能使这项工作吗?本来想看看true能不能重新定义,后来看到true居然是关键字

是否有可能 "fix" 模式错误并得到 "you-can't-assign-to-a-keyword-error"?

fn main() {
    let true = false;
}

我得到:

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

Playground

我不确定你想做什么或者你为什么想要这样做!如果一种语言允许您重新定义 truefalse,大多数人会认为这是一个设计缺陷,我相信这至少是 The Daily WTF.[= 一期的主题。 18=]

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

常量定义不允许模式,因此您可以通过尝试将 true 重新定义为 const:

来获得不同的错误
const true: bool = false;

这会产生一个更类似于您之后的错误:

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

错误信息没有问题。您在 let 绑定中使用 refutable pattern,并且 let 只允许无可辩驳的模式。

换句话说,当您这样做时:

let variable = value

您没有为变量赋值。您正在创建一个绑定,其中左侧与右侧的内容相匹配。它应该是一个无可辩驳的模式,因为匹配必须总是成功。