Rust: Nested type parameter should not count as unconstrained

Created on 7 Feb 2017  路  2Comments  路  Source: rust-lang/rust

trait Foo<T> {
    fn method() -> T;
}

struct Bar<T>(T);

impl<A, B: Foo<A>> Bar<B> {

}
7 | impl<A, B: Foo<A>> Bar<B> {
  |      ^ unconstrained type parameter

When we have a value Bar(foo), both A and B is known, so should not consider A is an unconstrained type parameter.

Most helpful comment

Change trait Foo<T> {} to trait Foo {type Out;} is a big change affecting lots of code and publish API.

  1. What's the semantic difference between impl<A, B: Foo<A>> and impl<A, B: Foo<Out = A>>?
  2. If whether A is X or Y is irrelevant in the code, can we relax the constrain checking?
  3. It might be better to provide a new syntax impl<Foo<_>> if nested type parameter is irrelevant.

All 2 comments

A type can have multiple impls of a parameterized trait simultaneously (impl Foo<X> for T and impl Foo<Y> for T where X!=Y, etc), hence you need to constrain A somehow.

If you want only one Foo impl to exist for a type, use associated type.

trait Foo {
    type Out;
    fn method() -> Self::Out;
}

struct Bar<T>(T)

impl<A, B: Foo<Out = A>> Bar<B> {
}

Change trait Foo<T> {} to trait Foo {type Out;} is a big change affecting lots of code and publish API.

  1. What's the semantic difference between impl<A, B: Foo<A>> and impl<A, B: Foo<Out = A>>?
  2. If whether A is X or Y is irrelevant in the code, can we relax the constrain checking?
  3. It might be better to provide a new syntax impl<Foo<_>> if nested type parameter is irrelevant.
Was this page helpful?
0 / 5 - 0 ratings