Parametric object-safe trait and how to deal with the pain of multiple impls?

We have a trait like

/// A source of data of some specified kind.
pub trait DataSource<T: Kind>: DataSourceBase {
    /// Returns the value associated with this kind.
    fn get_values(&self) -> T::Values;

    /// Same as `get_values` but only available for kinds with only one value.
    fn get_value(&self) -> Option<T> where T: Kind<Values=Option<T>> {
        self.get_values()
    }
}

But if a type is both DataSource<Title> and DataSource<Url>, then we can't call foo.get_value(). The only alternative seems to be <Foo as DataSource<Title>>::get_value(&foo) which kinda sucks because it forces us to write the type (Foo) and add in the &. Any way to not have to do that? (Really wish <foo as DataSource<Title>>.get_value() was a thing, but anyway...)

We guess we could do (&foo as &dyn DataSource<Title>).get_value() but not sure if the compiler can optimize that.

Is there a reason you can't just specify the return type?

let url: Option<Url> = implementer.get_value();
2 Likes

Huh, didn't realize that would work through ok_or_else and such. And it's cleaner. 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.