Search code examples
rustwhere-clausetraits

How do I specify a where clause that says that a passed type's reference can be converted to another one in Rust?


I need to express that a reference to a certain type parameter can be converted to a reference to another one.

Example:

trait TestTrait {}

struct TestStruct {}

impl TestTrait for TestStruct {}

fn test<Trait: ?Sized, Type>(object: &Type) -> &Trait
    where ... 
{
    object
}

fn call_test()
{
    let object = TestStruct{};

    let t = test::<dyn TestTrait, TestStruct>(&object);
}

What do I need to put in the where clause?

EDIT: I don't want to be implementing From, AsRef, etc. I've considered those.


Solution

  • On nightly, you can use Unsize:

    #![feature(unsize)]
    
    fn test<Trait: ?Sized, Type>(object: &Type) -> &Trait
    where
        Type: std::marker::Unsize<Trait>,
    {
        object
    }
    

    Note that this will also accept other coercions, e.g. arrays to slices.

    On stable, I don't think there is a way to achieve that.