Syntax Doubts: Trait Bound, Implementation Declaration

Questions are about the syntax of trait bounds. Take the example:

// Valid T must implement the trait Trait
struct Example<T: Trait> {
  value: T
}

If we want to implement a method on it:

impl<T:Trait> Example<T> {
  fn something (){ } 
}
  1. Why isn't T:Trait inferred, so that we only need impl<T> Example <T>? In other words, is this necessary or is it a decision for improving code-readability?

LLM answer: "The compiler does not look into the struct’s definition to fetch its bounds. " (which as OP I am aware, but does not answer why.)

Now a closely related example:

impl<T:Display, U:Trait> SomeTrait<T> for Example<U> { }

But this should be allowed:

impl<T, U> SomeTrait<T> for Example<U> { }

Rust could infer: whatever is used on Example<U> is already assumed to have Trait implemented.

Last closely related example. This is forbidden:

impl<T:Trait> A {
  fn something(a:T) {}
}

Was confusing as well. But I do get that if T is only used into a function using it in the impl<T:Trait> looks hierarchically / semantically incorrect.

There's an RFC that (I believe) would address this:

But nobody has implemented it.

It’s something of a convention in Rust to not have trait bounds in the type definition unless actually needed (eg. to refer to an associated type), in order to avoid repetition and to make the type more flexible. Bounds should be method or impl block specific and minimal in the sense that a method shouldn’t have bounds that it doesn’t use.

However, this does make typer less self-documenting at a glance; it’s not immediately clear whether a value of some Foo<T> is useful in any way even if you can construct one.

Here's a blog post about implied bounds. Long story short, it's not a slam-dunk always-good feature, because it introduces SemVer hazards. Ideally the author could choose which bounds are guaranteed (and thus implied) or not.

3 Likes

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.