Why is it possible to return a mutable reference to a literal from a function?

99封情书 提交于 2019-12-12 12:28:17

问题


The current edition of The Rustonomicon has this example code:

use std::mem;

pub struct IterMut<'a, T: 'a>(&'a mut [T]);

impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;

    fn next(&mut self) -> Option<Self::Item> {
        let slice = mem::replace(&mut self.0, &mut []);
        if slice.is_empty() {
            return None;
        }

        let (l, r) = slice.split_at_mut(1);
        self.0 = r;
        l.get_mut(0)
    }
}

I'm confused about this line in particular:

let slice = mem::replace(&mut self.0, &mut []);
//                                    ^^^^^^^ 

How does this borrow check? If this were an immutable borrow, RFC 1414 indicates that the [] rvalue should have 'static lifetime, so that an immutable borrow would borrow-check, but the example shows a mutable borrow! It seems that one of two things must be going on:

  • Either [] is a temporary (so that it can be used mutably), in which case it would not have 'static lifetime, and should not borrow-check;
  • Or that [] has 'static lifetime, and therefore it should not be possible to take a mutable borrow (since we don't guarantee exclusive access as we take the borrow), and should not borrow-check.

What am I missing?

Related:

  • Why can I return a reference to a local literal but not a variable?

    This question focuses on immutable references; this question is about mutable references.

  • Why is it legal to borrow a temporary?

    This question focuses on taking references inside of a function; this question is about returning a reference.

来源:https://stackoverflow.com/questions/56066534/why-is-it-possible-to-return-a-mutable-reference-to-a-literal-from-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!