Skip to content

Lifetime mismatch with Option as_mut and map #91292

Open
@Yuri6037

Description

@Yuri6037

Consider the following code:

use std::ops::DerefMut;
use std::ops::Deref;

pub trait SectionData: std::io::Read + std::io::Write + std::io::Seek {}

pub struct SectionMut<'a>
{
    data: &'a mut Option<Box<dyn SectionData>>,
}

impl<'a> SectionMut<'a>
{
    pub fn open(&mut self) -> Option<&mut dyn SectionData>
    {
        //self.data.as_mut().map(|v| v.deref_mut()) //Lifetime mismatch
        match &mut self.data { //Works
            Some(v) => Some(v.deref_mut()),
            None => None
        }
    }

    pub fn open1(&self) -> Option<&dyn SectionData>
    {
        self.data.as_ref().map(|v| v.deref()) //Works
    }
}

I find it strange that a match statement works but not the map function with as_mut. On the IRC a user found a way to fix it by replacing Option<&mut dyn SectionData> with Option<&mut dyn SectionData + 'static>. Which is also weird considering 'static is supposed to be implicit. What's also weird is this works perfectly with as_ref alone.

EDIT: I could track the issue down to dyn (again). When removing the dyn SectionData and replacing it with a concrete struct everything works fine.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceA-lifetimesArea: Lifetimes / regions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions