-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement operator overriding for ==
and !=
#7742
Comments
What do you think about this? @medvednikov |
Yes, custom != and == are fine. |
@hungrybluedev currently V supports |
@Delta456 @medvednikov it's planned to allow override all of the oprators? |
No because the user has to write readable code, we shouldn't be going like how C++ did. 🙂 |
Yeah that's because @Delta456 recently added support for it. :) Once |
Well, that's not generally true as it would harm performance - imagine e.g. comparison of approximate numbers (like any float). There you want to implement |
@dumblob Your concerns about floating points are correct. But I believe V already uses an internal epsilon for comparison of floating points. We need to see if that is sufficient. Also, on Discord, we discussed about reducing needless duplication.
The comparison function returns 0 if two structs are equal, a negative integer if the parameter is "larger" or a positive integer if the parameter is "smaller". Just like in the Comparable interface for Java. |
It does not 😉 (as is visible from the PR I linked above - #5180 (comment) ). Thus currently any float comparisons in V are undefined. But this topic shouldn't be discussed here (but rather in vlang/vtl#2 or vlang/vtl#2 ).
Hm, that makes sense from the API stand point. The only downside is performance ( |
Implemented in 9033099 |
Currently, V supports overloading the arithmetic operators for structs. These include
+
,-
,/
, and*
. There are plans to support<
and>
as well. However,==
and!=
are generated automatically for the structs. While this is a practical solution that covers several cases, there remain some examples where a custom implementation by the user would be beneficial.For instance, assume a struct
Fraction
with membersn
andd
. The compiler is most likely to compare the corresponding elements and call it done. However, the better way to compare two fractions (sayf
andg
) is to cross-multiply the numerators and denominators (likea = f.n * g.d
andb = g.n * f.d
) and then compare them (a == b
).This problem generally extends to cases where two structs can be equal even if their components are not. It can be argued that the structs in question could be designed better to avoid having differing internals. However, it is not always feasible or possible to do so. There could be several reasons for that, like performance, lazy evaluation, and so on.
The text was updated successfully, but these errors were encountered: