Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type annotations needed for `&Borrowed`

Tags:

rust

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.

like image 436
Jerry Yuan Avatar asked Jun 21 '26 16:06

Jerry Yuan


2 Answers

  1. Your code is fine. I passed 98' by you code without any change.
    enter image description here

  2. 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~
    enter image description here

like image 118
Jason Avatar answered Jun 23 '26 08:06

Jason


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.

like image 28
陈靖珏 Avatar answered Jun 23 '26 10:06

陈靖珏



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!