Support for implementing reference trait and mut ref trait for struct

trait temp_trait{
    fn ref_func(&self);
    fn take_owner(self);
    fn nothing();
}
struct A;
struct B;
//how traits are ussaly implemented
impl temp_trait for A{
    fn ref_func(&self){todo!()}
    fn take_owner(self){todo!()}
    fn nothing(){todo!()}
}
//the feature I want to see
//In the language
impl &temp_trait for B{
//Only implement all the the function that at
//most take reference of the initiated struct.
    fn ref_func(&self){todo!()}
    fn nothing(){todo!()}
//Don't need to implement take_owner() function
//As it will own the value
}

fn func1<T:temp_trait>(input:&T){todo!()}

let main(){
    let var1=A;
    let var2=B;
    func1(var2);
    func1(&var1);
}


this is ussaly necessary when my struct lets say B contains a reference to other struct A which implement the DemoTrait trait

trait Demotrait{}
struct A;
impl Demotrait for A{}
//B is a wrapper around &A
struct B<'a>{
reference:'a &A;
}
//As B is a wrapper around &A it should implement 
//&Demotrait other than Demotrait.
impl &Demotrait for B{}
fn func1<T:Demotrait>(input:&T){todo!()}
fn main(){
let var1=A;
let var2=B{reference:&A}
func1(&var1);
func1(var2);
}

As long for now I have to create two seperate trait for struct A and struct &A which include a lot of boilerplate.

Having two traits seems like the right approach here, but I'm not sure why you say there's a lot of boilerplate. Merely making the "borrowing" trait a supertrait of the "owning" trait should be sufficient?

trait BorrowingTrait {
    fn ref_func(&self);
    fn nothing();
}

trait OwningTrait: BorrowingTrait {
    fn take_owner(self);
}

struct A;
struct B;

impl BorrowingTrait for A {
    fn ref_func(&self) { todo!() }
    fn nothing() { todo!() }
}

impl OwningTrait for A {
    fn take_owner(self) { todo!() }
}

impl BorrowingTrait for B {
    fn ref_func(&self) { todo!() }
    fn nothing() { todo!() }
}

Alternatively, perhaps you want to impl YourTrait for &B, in which case self in take_owner will be of type &B.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.