Equality
Equality
Move supports two equality operations ==
and !=
Operations
==
equal
Returns true
if the two operands have the same value, false
otherwise
!=
not equal
Returns true
if the two operands have different values, false
otherwise
Typing
Both the equal (==
) and not-equal (!=
) operations only work if both operands are the same type
Equality and non-equality also work over user defined types!
If the operands have different types, there is a type checking error
Typing with references
When comparing references, the type of the reference (immutable or mutable) does not matter. This means that you can compare an immutable &
reference with a mutable one &mut
of the same underlying type.
The above is equivalent to applying an explicit freeze to each mutable reference where needed
But again, the underlying type must be the same type
Restrictions
Both ==
and !=
consume the value when comparing them. As a result, the type system enforces that the type must have drop
. Recall that without the drop
ability, ownership must be transferred by the end of the function, and such values can only be explicitly destroyed within their declaring module. If these were used directly with either equality ==
or non-equality !=
, the value would be destroyed which would break drop
ability safety guarantees!
But, a programmer can always borrow the value first instead of directly comparing the value, and reference types have the drop
ability. For example
Avoid Extra Copies
While a programmer can compare any value whose type has drop
, a programmer should often compare by reference to avoid expensive copies.
This code is perfectly acceptable (assuming Foo
has drop
), just not efficient. The highlighted copies can be removed and replaced with borrows
The efficiency of the ==
itself remains the same, but the copy
s are removed and thus the program is more efficient.
Last updated