fn recursive_binary_search<T: Ord>(list: &mut [T], target: T) -> bool {
if list.len() < 1 {
return false;
}
let guess = list.len()/2;
if target == list[guess] {
return true;
} else if list[guess] > target {
return recursive_binary_search(&mut list[0..guess], target);
} else if list[guess] < target {
return recursive_binary_search(&mut list[guess..list.len()], target);
}
}
编译器会引发上if target == list[guess]
一个错误说if语句类型不匹配拉斯特
src/main.rs:33:5: 39:6 error: mismatched types [E0308]
src/main.rs:33 if target == list[guess] {
^
src/main.rs:33:5: 39:6 help: run `rustc --explain E0308` to see a detailed explanation
src/main.rs:33:5: 39:6 note: expected type `bool`
src/main.rs:33:5: 39:6 note: found type `()`
error: aborting due to previous error
我无法弄清楚如何重写这个功能,以满足类型检查递归函数。我认为这是因为我有返回类型设置为布尔和有返回函数调用?
是不是Eq特质不必要? Ord包含PartialOrd + Eq。是的,当然这只是为了学习的目的。 – leshow
@leshow yep;我没有想到它就复制了它;在最后一个版本中删除了也修复了无限递归错误。 – Shepmaster
感谢与比赛的提示,这是一个很好的写作方法。 – leshow