How to design trait with Reference types and mutable reference types

I want to implement a trait on reference types and mutable reference types, like :

impl FromValue for &u8 {
    fn from_value(value: &'a mut ValueMap) -> Option<&u8>{
         todo!()
    }
}

impl FromValue for &mut u8{
     fn from_value(value: &'a mut ValueMap) -> Option<&mut u8>{
         todo!()
    }
}

One way I think of is:

pub trait FromValue: Sized {
    fn from_value(value: &mut ValueMap) -> Option<Self>;
}

but this have lifetime error.

playground link: Rust Playground

Can you provide the error and reproducible code for it?

Hi, this is playground , Rust Playground

I guess I know what you want. You need to add the lifetime to the trait definition.

#![allow(unused)]

pub struct ValueMap;

pub trait FromValue<'a>: Sized {
    fn from_value(value: &'a mut ValueMap) -> Option<Self>;
}

impl<'a> FromValue<'a> for &'a mut u8 {
    fn from_value(value: &'a mut ValueMap) -> Option<Self> {
        todo!()
    }
}

impl<'a> FromValue<'a> for &'a u8 {
    fn from_value(value: &'a mut ValueMap) -> Option<Self> {
        todo!()
    }
}

fn test(value_map: &mut ValueMap){
    let x: &mut u8 = <_>::from_value(value_map).unwrap();
}
2 Likes

Thanks ^-^

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.