top | item 44498755

(no title)

jhugo | 7 months ago

Because it doesn't know if you're relying on T being Clone in method bodies. The internal behavior of methods is not encoded in the type system.

discuss

order

saghm|7 months ago

You can already write method bodies today that have constraints that aren't enforced by the type definition though; it's trivially possible to write a method that requires Debug on a parameter without the type itself implementing Debug[0], for example. It's often even encouraged to define the constraints on impl blocks rather than the type definition. The standard library itself goes out of its way to define types in a way that allow only partial usage due to some of their methods having bounds that aren't enforced on the type definition. Rust's hashmap definition in the standard library somewhat notably doesn't actually enforce that the type of the key is possible to hash, which allows a hashmap of arbitrary types to be created but not inserted into unless the value actually implements Hash[1].

[0]: https://play.rust-lang.org/?version=stable&mode=debug&editio...

[1]: https://www.reddit.com/r/rust/comments/101wzdq/why_rust_has_...

enricozb|7 months ago

I'm not sure how these two things are related. When writing an `impl` for a struct, there's no assumption on the bounds of the generics (if any) unless they are specified _at the impl site_.

For example, the bounds of T in

    impl<T> Weird<T> {
      ..
    }
are independent of the bounds of `T` in any other impl or the struct definition.

Unless I'm missing something...