我可以用常量变量隐藏一个const绑定吗?

蒂姆·罗宾逊

我认为这可以工作:

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);

我是在做错什么,还是不能constlet相同的名字遮盖现有的绑定

蒂姆·罗宾逊

我想我明白了...当我使用时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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我想制作一个导航栏,可以用javascript隐藏和取消隐藏

我可以用一个以上的参数映射一个函数吗?

我可以用异步管道将 observable 解包到一个视图变量而不是 ngIf 吗?

我可以给ng-form一个可以用$ pristine检查的名称吗?

我可以用一个模块实现多种模块类型吗?

我可以用另一个分支的提交替换旧的提交吗?

我可以用Java做一个抽象的枚举吗?

写一个python脚本,我可以用随机模块做这个吗?

我可以用一个设备创建软件RAID 1吗?

我可以用另一个查询结果更改数组的值吗

我可以用git分割一个已经分割的块吗?

我可以用 gzip 创建一个 .Z 文件吗?

我可以用data.table在j上做一个明确的比较吗

我可以用constexpr函数声明一个静态数组吗

我可以用此代码编写一个可变大小的数组吗?

我们可以用C ++返回一个函数吗?

我可以用一个命令修复硬盘上的坏块吗?

我可以用 UILabels 做一个总计吗?

我可以用一个函数代替所有这些函数吗?

Java套接字:我可以用一个线程编写一个TCP服务器吗?

Kotlin:我可以用另一个函数覆盖一个函数吗?(如覆盖)

我可以用一种更优雅的方式对一个组件执行多项操作吗?

有人可以用一个简单的Perl脚本来帮助我吗

我可以用一个表达式引用多个正则表达式项吗?

我可以用另一个“POST”方法覆盖默认的表单提交方法“POST”吗?

我可以用一个窗口用bash打开另一个窗口并用鱼打开终结器吗?

从现在开始,我可以制作一个变量_const吗?

是否可以用CSS隐藏一个空的<table>行?

来自另一个静态常量变量的静态常量变量会导致编译错误?