I am trying to compile the LeetCode question 98's rust code in https://rustgym.com/leetcode/98
However, I receive an error in this line: let node = node.borrow();:
type annotations needed for `&Borrowed`
type must be known at this point
rustcE0282
s0098_validate_binary_search_tree.rs(66, 17): consider giving `node` the explicit type `&Borrowed`, where the type parameter `Borrowed` is specified
However, Leetcode has no problem to compile it. Here is the Code.
use std::rc::Rc;
use std::cell::RefCell;
type TreeLink = Option<Rc<RefCell<TreeNode>>>;
trait Inorder {
fn inorder(&self, visit: &mut dyn FnMut(i32));
}
impl Inorder for TreeLink {
fn inorder(&self, visit: &mut dyn FnMut(i32)) {
if let Some(node) = self {
let node = node.borrow();
Self::inorder(&node.left, visit);
visit(node.val);
Self::inorder(&node.right, visit);
}
}
}
impl Solution {
pub fn is_valid_bst(root: TreeLink) -> bool {
let mut prev: Option<i32> = None;
let mut res = true;
root.inorder(&mut |x| {
if let Some(y) = prev {
if x <= y {
res = false;
}
}
prev = Some(x);
});
res
}
}
I am using rustc 1.55.0 (c8dfcfe04 2021-09-06). I think it may be a bug in compiler.
Your code is fine. I passed 98' by you code without any change.

I met the same question by adding the redundant code use std::borrow::Borrow;. So when I deleted use std::borrow::Borrow;, everything is fine~

I had the same problem, after I checked, the culprit was the "clion" error auto-import, try to delete the "import" section and re-import, the problem should be solved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With