有没有办法使不可变的引用可变? [英] Is there a way to make an immutable reference mutable?

查看:199
本文介绍了有没有办法使不可变的引用可变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Rust中解决一个leetcode问题(从列表末尾删除第N个节点).我的解决方案使用两个指针来找到要删除的Node:

I want to solve a leetcode question in Rust (Remove Nth Node From End of List). My solution uses two pointers to find the Node to remove:

#[derive(PartialEq, Eq, Debug)]
pub struct ListNode {
    pub val: i32,
    pub next: Option<Box<ListNode>>,
}

impl ListNode {
    #[inline]
    fn new(val: i32) -> Self {
        ListNode { next: None, val }
    }
}

// two-pointer sliding window
impl Solution {
    pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
        let mut dummy_head = Some(Box::new(ListNode { val: 0, next: head }));
        let mut start = dummy_head.as_ref();
        let mut end = dummy_head.as_ref();
        for _ in 0..n {
            end = end.unwrap().next.as_ref();
        }
        while end.as_ref().unwrap().next.is_some() {
            end = end.unwrap().next.as_ref();
            start = start.unwrap().next.as_ref();
        }
        // TODO: fix the borrow problem
        // ERROR!
        // start.unwrap().next = start.unwrap().next.unwrap().next.take();
        dummy_head.unwrap().next
    }
}

我借用了链表的两个不可变的引用.找到要删除的目标节点后,我要删除其中一个并使另一个可变.以下每个代码示例均会导致编译器错误:

I borrow two immutable references of the linked-list. After I find the target node to remove, I want to drop one and make the other mutable. Each of the following code examples leads to a compiler error:

// ERROR
drop(end); 
let next = start.as_mut().unwrap.next.take();

// ERROR
let mut node = *start.unwrap()

我不知道这种解决方案是否可以用Rust编写.如果我可以使不可变的引用变得可变,该如何做呢?如果不是,那么在使借阅检查器感到满意的同时还能实现相同的逻辑吗?

I don't know if this solution is possible to be written in Rust. If I can make an immutable reference mutable, how do I do it? If not, is there anyway to implement the same logic while making the borrow checker happy?

推荐答案

有没有办法使不可变的引用变得可变?

Is there a way to make an immutable reference mutable?

否.

您可以编写不安全的Rust代码来强制类型对齐,但​​是该代码实际上是不安全的,并导致未定义的行为.你不要这个.

You could write unsafe Rust code to force the types to line up, but the code would actually be unsafe and lead to undefined behavior. You do not want this.

有关您的特定问题,请参阅:

For your specific problem, see:

  • How to remove the Nth node from the end of a linked list?
  • How to use two pointers to iterate a linked list in Rust?

这篇关于有没有办法使不可变的引用可变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆