【发布时间】:2021-09-17 01:44:25
【问题描述】:
我正在尝试在https://rustgym.com/leetcode/98 中编译 LeetCode 问题 98 的 rust 代码
但是,我在这一行收到错误: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
但是,Leetcode 编译它没有问题。这是代码。
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
}
}
我正在使用 rustc 1.55.0 (c8dfcfe04 2021-09-06)。我认为这可能是编译器中的错误。
【问题讨论】:
-
我不是 leetcode,但我也无法编译该代码,因为 TreeNode 和 Solution 未定义。您在此处发布的代码也与您链接的文章中的代码不同。
-
很难回答您的问题,因为它不包含minimal reproducible example。如果您尝试在Rust Playground 上重现您的错误,如果可能的话,这将使我们更容易为您提供帮助,否则在全新的 Cargo 项目中,然后在edit 您的问题中包含附加信息。有Rust-specific MRE tips 可以用来减少您在此处发布的原始代码。
-
C检查你是否导入了
Borrowtrait 并移除该导入。有时,当我键入some_ref-cell.borrow()并出现此错误时,Clion 会错误地自动导入它
标签: rust