可以迭代rc< lt; lt; t>>随便让

发布于 2025-01-31 03:44:43 字数 1261 浏览 1 评论 0原文

我正在实施一个LinkedList来了解智能指针。这是结构:

type Link<T> = Option<Rc<RefCell<Node<T>>>>;
struct Node<T> {
    value: T,
    next: Link<T>,
}

impl<T> Node<T> {
    pub fn new(value: T) -> Rc<RefCell<Node<T>>> {
        Rc::new(RefCell::new(Node { value, next: None }))
    }
}

struct LinkedList<T> {
    head: Link<T>,
}

实施推送方法时,我在node.next上遇到了一个问题,我可以通过使用循环进行迭代来解决此问题,例如 在转到下一个方法之前,我尝试使用时使用实现,但不起作用,我也不弄清楚原因。

let mut curr = Rc::clone(head);
while let Some(ref boxed) = curr.borrow().next {
    curr = Rc::clone(boxed);
}
// loop {
//     let next = match curr.borrow().next {
//         Some(ref boxed) => Rc::clone(boxed),
//         None => break,
//     };

//     curr = next;
// }

curr.borrow_mut().next = Some(node);

发生错误是因为curr.borrow()。进入下一个迭代时删除了下一个

有没有办法在时用实现它?

I was implementing an LinkedList to learn about smart pointers. This is the structures:

type Link<T> = Option<Rc<RefCell<Node<T>>>>;
struct Node<T> {
    value: T,
    next: Link<T>,
}

impl<T> Node<T> {
    pub fn new(value: T) -> Rc<RefCell<Node<T>>> {
        Rc::new(RefCell::new(Node { value, next: None }))
    }
}

struct LinkedList<T> {
    head: Link<T>,
}

While implementing the push method, I faced a problem with iteration over node.next and I could solve this by doing the iteration with a loop, like this thread.
And before I move on to the next method, I've tried to implement with while let, but doesn't work, and I don;t figure out why.

let mut curr = Rc::clone(head);
while let Some(ref boxed) = curr.borrow().next {
    curr = Rc::clone(boxed);
}
// loop {
//     let next = match curr.borrow().next {
//         Some(ref boxed) => Rc::clone(boxed),
//         None => break,
//     };

//     curr = next;
// }

curr.borrow_mut().next = Some(node);

The error occurs because the curr.borrow().next is dropped when go to the next iteration?

Is there a way to implement that with while let?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文