Rust: error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements

后端 未结 1 1146
别那么骄傲
别那么骄傲 2021-01-24 05:02

This is the minimal code:

struct Node {
    item: T,
    next: Link,
}

type Link = Option<         


        
相关标签:
1条回答
  • 2021-01-24 05:28

    We can rewrite your code as:

    struct Node<T> {
        item: T,
        next: Link<T>,
    }
    
    type Link<T> = Option<Box<Node<T>>>;
    
    pub struct IterMut<'a, T>(&'a mut Link<T>);
    
    impl<'a, T> Iterator for IterMut<'a, T> {
        type Item = &'a mut T;
        fn next(&mut self) -> Option<Self::Item> {
            if let Some(boxed_node) = self.0 {
                self.0 = &mut boxed_node.next;
                Some(&mut boxed_node.item)
            }
            else {
                None
            }
        }
    }
    

    You can see that boxed_node life end at the end of the function so you can't return a reference link to it.

    The solution is to take a reference of the box and not a reference to the option:

    struct Node<T> {
        item: T,
        next: Link<T>,
    }
    
    type Link<T> = Option<Box<Node<T>>>;
    
    pub struct IterMut<'a, T>(Option<&'a mut Box<Node<T>>>);
    
    impl<'a, T> Iterator for IterMut<'a, T> {
        type Item = &'a mut T;
        fn next(&mut self) -> Option<Self::Item> {
            if let Some(boxed_node) = self.0.take() {
                self.0 = boxed_node.next.as_mut();
                Some(&mut boxed_node.item)
            }
            else {
                None
            }
        }
    }
    

    You can also remove the Box:

    struct Node<T> {
        item: T,
        next: Link<T>,
    }
    
    type Link<T> = Option<Box<Node<T>>>;
    
    pub struct IterMut<'a, T>(Option<&'a mut Node<T>>);
    
    impl<'a, T> Iterator for IterMut<'a, T> {
        type Item = &'a mut T;
        fn next(&mut self) -> Option<Self::Item> {
            if let Some(boxed_node) = self.0.take() {
                self.0 = boxed_node.next.as_mut().map(AsMut::as_mut);
                Some(&mut boxed_node.item)
            }
            else {
                None
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题