[Solved]Returning generic container(Box or Arc)

Hello. I want do something like

trait Something {
    type Container:ContainerTrait<T=Self::T>;
    type T:SomeTrait;

    fn foo(v:Self::T) -> Self::Container{ //rust do not like Container<T>
        Self::Container::new(v);//using method of ContainerTrait
    }

    fn get(&self) -> Self::Continer{
        ...
    }
}

Container is Box,Rc,Arc, etc. but rust Rc, Box has no Container trait. Please, add it

And allow to return just T without any container

My understanding is that container/collections traits would need language features we do not yet have in order to be expressible.

Hey. I have found the solution.

use std::rc::Rc;
use std::ops::Deref;
use std::fmt::Display;
use std::borrow::Borrow;

trait MyTrait:Display{
    fn print(&self){println!("{}",self)}
   
}

trait Foo{
    type T:MyTrait;
    //type C:From<Self::T> + Deref<Target=Self::T>;
    //type C:From<Self::T> + Into<Self::T>;
    //type C:From<Self::T> + AsRef<Self::T>;
    type C:From<Self::T> + Borrow<Self::T>;
   
    //i32 does not implements AsRef and Deref
    //Into trait movs.
    //Borrow trait works!
   
   
    fn cool(v:Self::T) -> Self::C{
        Self::C::from(v)
    }
   
    fn print(v:Self::C){
        {
            v.borrow().print()
        }
       
        {
            v.borrow().print()
        }
    }
}


impl MyTrait for i32{
}

struct S;

//uses Box/Rc etc
impl Foo for S{
    type T=i32;
    type C=Rc<Self::T>;
}

//uses itself
struct V;

impl Foo for V{
    type T=i32;
    type C=i32;
}


fn main(){
    S::print(S::cool(4));
    V::print(V::cool(6));
}
1 Like