types - 为什么 rustc 说推断的类型不匹配?
问题描述
如果我尝试创建一个函数指针向量,编译器总是会抱怨错误的类型(尽管我没有明确声明任何类型):
fn abc() {}
fn def() {}
fn main()
{
let a = vec![abc, def];
}
error[E0308]: mismatched types
--> src/main.rs:5:13
|
5 | let a = vec![abc, def];
| ^^^^^^^^^^^^^^ expected slice, found array of 2 elements
|
= note: expected struct `Box<[fn() {abc}], _>`
found struct `Box<[fn(); 2], std::alloc::Global>`
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
error: could not compile `tes`
To learn more, run the command again with --verbose.
解决方案
我相信 Rust 试图为函数赋予唯一的类型,所以只需指定它是一个函数指针 Vec。这也避免了额外的间接和分配Box<dyn Fn()>
:
fn abc() {}
fn def() {}
fn main() {
let a: Vec<fn()> = vec![abc, def];
}
或者,可以推断出“cast”第一个和其余部分:
fn abc() {}
fn def() {}
fn main() {
let a = vec![abc as fn(), def];
}
推荐阅读
- proxy - VSTSNuGetPush.exe 代理设置
- r - 数据框之间的子集
- python - 如何在一个 Django 模型实例中存储两个整数?
- javascript - 从子无状态类组件访问来自父无状态功能组件的更新道具
- cmake - 将重复的 CmakeLists.txt 功能移动到公共文件
- wpf - 非常频繁地显示数据时的性能问题
- xml - omnet++解析xml文件
- encryption - 使用第三方工具混淆单个 Java 类文件
- javascript - React Native - 显示来自 API 的数据
- reactjs - 找不到“表单”属性 this.props.form 反应