Cannot assign to data in a `&` reference

I try to implement a question with Rust from leetcode "Remove Nth Node from List End" in one pass, but it seem to be hard to implement for share two mutable reference pointer to one reference as follow:

type Link = Option<Box<Node>>;
#[derive(Debug, Clone)]
pub struct Node {
	val: i32,
	next: Link,

fn remove_nth_from_end_list(head: &Option<Box<Node>>, n: i32) {
    let mut first = head;
    let mut second = head;

    for _ in 0..n {
        first = &(first.as_ref().unwrap().next);

    while let Some(_node) = first.as_ref() {
        first = &(first.as_ref().unwrap().next);
        second = &(second.as_ref().unwrap().next);

    // this line causes the error "cannot assign to data in a `&` reference"
    second.as_ref().unwrap().next = second.as_ref().unwrap().next.take().unwrap().next;


I also tried with Rc, RefCell, and Cell, it seems not to work as well for this case.
Can anyone guide me how to solve this issue?


I don’t see any easy “fix” without changing the Node type. For example if you wanted to use RefCell, that would need some use of RefCell throughout the data structure. But that would probably be a bit fiddly nontheless, so maybe spare that for when you’re a bit more experienced with the basics of Rust.

In this particular example I believe it would be much easier to find an approach that doesn’t require having two references at the same time. You’re basically already traversing the list twice anyways, how about instead of doing it in parallel, you do the first traversal first to find the index of the element you want to remove, only then start the second traversal to remove the element at that index?

Here's a version that uses RefCell. As @steffahn says it changes the structure of the code quite a bit. But I figured it might be helpful for you to see an example of what it might look like.

Playground Link

Thanks for the helping example :slightly_smiling_face:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.