RequireKeys
RequireKeys

Reputation: 538

What happens when I don't satisfy trait bounds?

I have some code :

impl<K, V> Database<K, V>
where
    K: Eq + Hash,
    V: Clone,

Where I have Database defined like :

pub struct Database<K, V>
where
    K: Eq + Hash,

Note the absence of trait bounds on V. My question is what happens if I construct an instance of this object such that V: !Clone? Would my methods that depend on V: Clone simple panic? Or will the rust compiler catch it?

Upvotes: 3

Views: 109

Answers (1)

Peter Hall
Peter Hall

Reputation: 58705

You can read this:

impl<K, V> Database<K, V>
where
    K: Eq + Hash,
    V: Clone,
{
    // methods
}

As:

Implement these methods for Database<K, V> whenever K implements Eq + Hash and V implements Clone.

If those constraints are not met then those methods will not exist, and you'll see a compile error if you try to call them.

These constraints are different from the ones on the type itself. Those just affect if you can construct an instance of the type. It's actually quite common to omit all constraints on the type itself and only have them on the impl blocks.

Upvotes: 4

Related Questions