Wrapper Owned for impl Deref

⚓ Rust    📅 2026-03-27    👤 surdeus    👁️ 1      

surdeus

Owned is a simple wrapper for Deref and DerefMut, but it can be useful

use std::ops::{Deref, DerefMut};

// Wrapper for Deref an DerefMut
#[derive(Debug, Clone, Copy, Default)]
pub struct Owned<T>(pub T);

impl<T> Deref for Owned<T> {
    type Target=T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for Owned<T> {

    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T> From<T> for Owned<T> {
    fn from(value: T) -> Self {
        Self(value)
    }
}

Then one can feel free to use impl Deref.

/// want ref of something may be large
pub trait Atrait<const N:usize> {
	type Output<'a>:Deref<Target = [usize;N]> where Self: 'a;
	fn get_array<'a>(&'a self)->Self::Output<'a>;
}
/// return ref
pub struct Astruct1<const N:usize>(pub [usize;N]);
impl<const N:usize> Atrait<N> for Astruct1<N> {
	type Output<'a>=&'a [usize;N];

	fn get_array<'a>(&'a self)->Self::Output<'a> {
		&self.0
	}
}
/// generate
pub struct Astruct2(pub usize);
impl<const N:usize> Atrait<N> for Astruct2 {
	type Output<'a>=Owned<[usize;N]>;

	fn get_array<'a>(&'a self)->Self::Output<'a> {
		Owned(array::from_fn(|v|v+self.0))
	}
}

pub fn want_array<T>(a:T)
	where T:Atrait<100>
{
	let binding = a.get_array();
	let arr: &[usize; 100]=binding.deref();
	let b=arr.split_at(10).0;
	println!("{:?}",b);
}

#[test]
fn test_want_array(){
	want_array(Astruct1(array::from_fn(|v|v)));
	want_array(Astruct2(10));
}

But what if one want owned value?

pub trait IntoOwned<T> {
	fn into_owned(self)->T;
}

impl<T> IntoOwned<T> for T {
	fn into_owned(self)->T {
		self
	}
}

impl<'a,T:Clone> IntoOwned<T> for &'a T {
	fn into_owned(self)->T {
		self.clone()
	}
}

impl<T> IntoOwned<T> for Owned<T> {
	fn into_owned(self)->T {
		self.0
	}
}

pub fn want_array_owned<T>(v:T)
	where for <'a> T:Atrait<10,Output<'a> : IntoOwned<[usize;10]>>
{
	let arr:[usize;10]=v.get_array().into_owned();
	println!("{:?}",arr);
}

#[test]
fn test_want_array_owned(){
	want_array_owned(Astruct1(array::from_fn(|v|v)));
	want_array_owned(Astruct2(10));
}

playground

1 post - 1 participant

Read full topic

🏷️ Rust_feed