rust - 预期类型与收到的类型不匹配
问题描述
我是生锈的新手,我正试图弄脏我的手,所以我试图实现快速排序,作为“The Book”练习之一的一部分(可能作者不打算建议虽然如此深入,但这不是最好的学习方式吗?:))
这就是我到目前为止所拥有的:
fn quicksort(v: &mut Vec<i32>) {
// helper funtions for sorting the partitional vectors
fn partition(v: &mut Vec<i32>, lo: i32, hi: i32) {
// pivot
let mut p: i32;
let mut i = lo;
for j in i..hi {
}
}
fn quicksort(v: &mut Vec<i32>, lo: i32, hi: i32) {
// pivot
let mut p: i32;
if lo < hi {
p = partition(v, lo, hi);
}
}
quicksort(v, 0, (v.len() -1).try_into().unwrap())
}
当我尝试编译时,我得到了这个:
[foo12@archT520 vectors]$ cargo run
Compiling vectors v0.1.0 (/home/foo12/programs/rust/book/vectors)
error[E0308]: mismatched types
--> src/main.rs:36:10
|
36 | p = partition(v, lo, hi);
| ^^^^^^^^^^^^^^^^^^^^ expected `i32`, found `()`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
error: could not compile `vectors`
To learn more, run the command again with --verbose.
我不明白我在搞砸什么。
另外,我很高兴获得不使用其他库的快速排序的完整实现。或许我可以从中吸取教训。
编辑:我也不确定这种使用函数名称“quicksort”的“阴影”方式是否可行。我之前更改过它,所以这不是错误的原因,但我想看看它是否会这样工作,这就是我这样离开它的原因。
解决方案
你fn partition(v: &mut Vec<i32>, lo: i32, hi: i32)
没有返回任何东西(在 Rust 中表示为具有返回类型()
),所以你不能将结果分配给类型的变量i32
。
推荐阅读
- python - 尝试使用“load_model”,但他创建了 0 层的新模型
- java - 如何使用 stripe-java 或 rest api 获取产品计划
- rust - 如何在 Rust 中使用可变迭代器管理所有权
- python - Numpy:检查一维数组是否是另一个数组的子数组
- javascript - 我可以为 windows 打包,但如果我想为 mac 打包,我会不断收到错误消息
- typo3 - CropViewHelper 显示 HTML 标签
- android - gradlew installdebug 未在设备上安装 apk。该怎么办?
- godot - 如何在 Godot 退出时保存游戏数据
- angular - storeFreeze 和 ngrx8
- php - 在 Laravel 中有很多关系的表格中显示一列