Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

rust - Why does this fail to compile?

I'm trying to get a reference to the tail of a linked list, and here's the code I wrote:

pub struct ListNode {
    pub next: Option<Box<ListNode>>,
}

fn tail(mut head: &mut Option<Box<ListNode>>) -> &mut Option<Box<ListNode>> {
    while let Some(x) = head.as_mut() {
        head = &mut x.next;
    }
    head
}

This fails to compile because it thinks I'm borrowing head as mutable twice. I was able to get to compile by changing it to this:

fn tail(mut head: &mut Option<Box<ListNode>>) -> &mut Option<Box<ListNode>> {
    while head.is_some() {
        head = &mut head.as_mut().unwrap().next;
    }
    head
}

It appears to me that these two functions do the exact same thing, but the first one looks a lot cleaner. Why doesn't it compile? Is there a better way of doing this than what I changed it to?

question from:https://stackoverflow.com/questions/65894176/why-does-this-fail-to-compile

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You already have a value of the correct reference type, so the as_mut is unnecessary.

while let Some(x) = head {
    head = &mut x.next;
}
head

I can't speak to why your first example doesn't compile, as I'm still no expert in speaking "borrow checker" myself, but my guess is that Rust is just being conservative and assuming that the head.as_mut() borrow lasts into the variable x, which gets put into head, and therefore is a mutable borrow lasting as long as head does, whereas when we directly access it as I do above, Rust is smart enough to understand what's really happening.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

1.4m articles

1.4m replys

5 comments

56.9k users

...