可以迭代rc< lt; lt; t>>随便让
我正在实施一个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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论