我可以用局部变量隐藏 const 绑定吗?
Can I shadow a const binding with a local variable?
我认为这行得通:
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);
但是:
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)
这个有效:
const x: &str = "10";
let y: i32 = x.parse().unwrap();
assert_eq!(10, y);
这也是:
let x: &str = "10";
let x: i32 = x.parse().unwrap();
assert_eq!(10, x);
我是不是做错了什么,还是无法用同名的 let
隐藏现有的 const
绑定?
我想我明白了...当我使用 let SOME_CONST
时,编译器认为我在进行模式匹配。
当我修复类型时:
const x: i32 = 10;
let x: i32 = x + 1;
assert_eq!(11, x);
我得到一个不同的错误:
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
就好像我把程序中所有出现的 x
都取出来并将它们扩展为常量 10
:
let 10: i32 = 10 + 1;
assert_eq!(11, x);
我认为这行得通:
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);
但是:
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)
这个有效:
const x: &str = "10";
let y: i32 = x.parse().unwrap();
assert_eq!(10, y);
这也是:
let x: &str = "10";
let x: i32 = x.parse().unwrap();
assert_eq!(10, x);
我是不是做错了什么,还是无法用同名的 let
隐藏现有的 const
绑定?
我想我明白了...当我使用 let SOME_CONST
时,编译器认为我在进行模式匹配。
当我修复类型时:
const x: i32 = 10;
let x: i32 = x + 1;
assert_eq!(11, x);
我得到一个不同的错误:
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
就好像我把程序中所有出现的 x
都取出来并将它们扩展为常量 10
:
let 10: i32 = 10 + 1;
assert_eq!(11, x);