Stream: general

Topic: "type parameter not constrained"

RalfJ (Oct 11 2019 at 12:12, on Zulip):

Can someone explain why the following is rejected by rustc? It compiles something to be "not constrained", but it's as constrained as I can make it...

pub trait FooTrait {
    fn compute(&self) -> i64;

impl<U: FooTrait, T: AsRef<U>> FooTrait for Vec<T> {
    fn compute(&self) -> i64 {
        self.iter().map(|x| x.as_ref().compute()).sum()

Playground link

RalfJ (Oct 11 2019 at 12:13, on Zulip):

This is related to which unfortunately also did not attract any expert that could explain what is happening why

oli (Oct 11 2019 at 12:15, on Zulip):

is the problem that there could be e.g. AsRef<i32> and AsRef<String> impls for T, so calling AsRef becomes useless because you'd still be generic?

rkruppe (Oct 11 2019 at 12:16, on Zulip):

My intuition is that the problem is the query posed to the trait system that would be answered using this trait (e.g., Vec<?0> : FooTrait, solving for ?0) gives no hint as to what U should be but the choice of U affects which code runs.

oli (Oct 11 2019 at 12:25, on Zulip):

cc @WG-diagnostics I think this error could benefit from a bit more explanation

pachi (Oct 11 2019 at 13:47, on Zulip):

@RalfJ Couldn't you remove U and constrain T like this: T: AsRef<dyn FooTrait> ? You're only telling that T can be converted to a reference to a FooTrait object, aren't you?

pachi (Oct 11 2019 at 13:47, on Zulip):

So you would have: impl<T: AsRef<dyn FooTrait>> FooTrait for Vec<T>

RalfJ (Oct 12 2019 at 13:58, on Zulip):

@pachi that impl however would not be useful if you have a Vec<Foo> where Foo: FooTrait

RalfJ (Oct 12 2019 at 13:58, on Zulip):

as we do not have anything like Foo: AsRef<dyn FooTrait>

Last update: Aug 13 2020 at 09:15UTC