Trait returning &Self

⚓ rust    📅 2025-06-09    👤 surdeus    👁️ 1      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Trait returning &Self

Hi, I have a following problem, I need to implement the trait IsType for the Wrapper structure. But I was unable to implement the from_ref and from_mut functions. At this point I am not even sure if it's possible to do. Any suggestions, including unsafe Rust are welcomed. Also the OriginalStruct and IsType cannot be altered. The Wrapper structure can be altered in any way possible, the main constraint, is that it has to implement the IsType trait.

// the following structure and trait cannot be altered
#[derive(Clone)]
struct OriginalStructure {
    pub data: u32,
}

trait IsType<T> {
    fn from_ref(t: &T) -> &Self;

    fn into_ref(&self) -> &T;

    fn from_mut(t: &mut T) -> &mut Self;

    fn into_mut(&mut self) -> &mut T;
}

// This is the wrapper, which can be changed.
// It must implement the IsType trait
#[derive(Clone)]
struct Wrapper(pub *mut OriginalStructure);
impl Wrapper {
    pub fn wrap(orig: OriginalStructure) -> Self {
        let orig = Box::into_raw(Box::new(orig));
        Self(orig)
    }
}

impl IsType<OriginalStructure> for Wrapper {
    fn from_ref(t: &OriginalStructure) -> &Self {
        todo!()
    }

    fn into_ref(&self) -> &OriginalStructure {
        todo!()
    }

    fn from_mut(t: &mut OriginalStructure) -> &mut Self {
        todo!()
    }

    fn into_mut(&mut self) -> &mut OriginalStructure {
        todo!()
    }
}

5 posts - 2 participants

Read full topic

🏷️ rust_feed