Hacker News new | ask | show | jobs
by Ar-Curunir 2176 days ago
Rust tends to take the second approach as well; it tends to place trait bounds on `impl` blocks, and not on the struct itself.

(This is by no means a standard across the community though; I'd say it's a 50/50 split)

1 comments

A case where it is unavoidable is when you want to refer to an associated type in your struct declaration.

In most other cases, putting bounds on impls leads to less repetition of those bounds and better error messages!

Another related topic is trait methods with method-level type parameters that have bounds. Those have to be repeated on every usage site so it is usually preferable to go for a design that has the type parameters in the actual trait.

Instead of:

    trait Foo {
        fn foo<T: Bar>(&self, bar: T)
    }
do this instead:

    trait Foo<T> {
        fn foo(&self, t: T)
    }

    impl<T: Bar> Foo for XYZ {
        fn foo(&self, bar: T) {

        }
    }
One bound might seem fine in this example but once stuff needs to be Send, Sync and 'static is when it gets annoying.