Hacker News new | ask | show | jobs
by coolThingsFirst 17 days ago
show me operator overloading in Zig
5 comments

In critical low-level code, any kind of overloading - operator or otherwise - is something you'd rather not have.

By expressivity I don't mean what characters you use in the conrecte syntax, but the number of lines needed to express an algorithm (up to a small constant). C doesn't have C++'s expressivity because it lacks templates, and while you can sort of express that kind of thing with macros, it's not all the way there. Zig, however, gets you all the way there (you might need to write matrix_plus instead of +, but the expressivity is the same).

BS. Using operator overloading with SIMD makes it easier to translate algorithms into code. I wrote my own U8x32 wrappers and a + b is way better than a.add(b).
I'm not disputing that some people like user-controlled operator overloading (Zig does have + etc. for vectors), but clearly others prefer no user-controlled overloading of any kind (don't know what the LLMs prefer, if they have any preferences at all). In the safety-critical space where I once worked, where people could get hurt or die if there's a stack overflow, the more common preference was against (user-controlled) overloads or any implicitness. That's why we need options.
Fair, but don't conflate custom operators with overloading just because C++ happened to have one very specific way of implementing custom operators.
I think zig would do to have "custom binary operators" which is not operator overloading, but basically give people what they want. It would suffice to be syntactic sugar elaborated by the parser. For example:

    const @<+> = @import("op.zig").special_add;

    const c = (a <+> b);
    //syntactic sugar for @<+>(a, b)
Maybe it will add that. But just how important that is, though, I'm not so sure. Languages like Java, C, and Go don't currently offer custom infix operators, and they are more popular than many languages that do.

Note that there are some complexities, though, to infix operators regarding the order of operations (e.g. + vs * in ordinary mathematical notation) and associativity (e.g. is `(x <+> y) <+> z` equal to `x <+> (y <+> z)`?). They can be dealt with, of course, but not without adding complexity that may or may not be worth it.

Just require parenthesis
The example you choose is rather telling, though. It indicates that the use case you have in mind is not at all the one that Zig is targeting.

A more humble critique would be to just acknowledge that you don’t seem to be a member of Zig’s target audience, and move on.

I am in the target audience. I do want low level systems programming.

Saying "you don't want operator overloading" in such cases is a reductionist view of how systems programming should look.

I’ll admit I interpreted that “you” in pron’s sentence to be a colloquial “you” and not an imperative one. So, more of a statement of their own preference than a strong statement of how things should be.

The point is, it’s a tradeoff. With overloading, exactly which code executes on a specific line becomes a bit more implicit because it depends on extra information from the surrounding context: the types of the arguments.

That comes with the usual tradeoffs. On the one hand, you could argue that the compiler is taking care of it for you, which saves the programmer from having to manually deal with it, and removes some visual clutter from the code.

But you can also argue that letting the choice of function be implicit means that a programmer who wants/needs to keep track of exactly what every line of code is doing needs to carry all that contextual information in their own head, too. For this programmer, it’s adding to the mental burden.

I don’t think it’s a coincidence that Kelley constantly brings up how Zig was inspired by difficulties writing a digital audio workstation with very hard real-time requirements. Part of what he’s doing there is giving a motivating case for why he wants to be an absolute control freak about, e.g., micro-managing exactly when memory is allocated and deallocated. That’s something only a subset of systems programmers need, because not all systems programming is dealing with things like hard real-time.

> The point is, it’s a tradeoff. If it's a trade off it's highly squewed.

>But you can also argue that letting the choice of function be implicit means that a programmer who wants/needs to keep track of exactly what every line of code is doing

Use LSP/IDE then ctrl+click operator. Boom. You see what it's executing.

Idea is to create abstraction that make it easier to operate on a more complex level. If you need that level of micro-managing just stick to assembly.

To be fair, the impression is that you want to do low level systems programming in Rust. It's a fine preference but it does put you in a different audience
I'm doing it in Rust because it's the closest to my ideal language. Not saying Rust is ideal.
You can do a+b in Zig with SIMD vectors. No operator overloading required
Sure. But doesn't it still lack autodiff, quaternions, etc?
In C++, the practical AD approach for large existing code-bases is operator-overloading. Swapping double for an active class, overload all math operations for this type, recording the computational graph on a tape, and then run the tape backwards for computing derivatives. This only works because operator-overloading and templates are language features.

Zig has no operator overloading, so tape-based AD means rewriting arithmetic as functon calls. Its compile-time code gen could instead do source transforamtion (like Enzyme / Tapenade, etc), which is a different trade-off.

Concrete example: With operator-overloading in C++, the Black-Scholes d1 expression, a statement with 5-inputs and 10 math operations, can be recorded with 10 nodes and operand links on tape. If adding expression templates, this reduces to a single tape entry function call, the rest is handled by the compiler. And the code is still readable like the original with double type.

Yes, there are definitely other use cases that Zig doesn't support (which some may view as a good or bad thing). I just wanted to respond to the comment about basic SIMD since the example was U8x32 and operator+, which Zig can do.
Point wasn't about SIMD, but defining my wrapper for it and giving it operations I needed.

Which seems to be something Zig can't do.

Hell, you can define operators for generic length SIMD lane.

Same goes for any bitwise operation <<, >>, &, |, %.

Can I write my SIMD/number abstraction and have it work?

Let's say I need rotors. With six dimensions. Can I overload it's basic numeric operations?

You need to understand that the things you want to do are the very things that others want their language to ensure cannot be done. For example, the question I'm asking is, can your preferred language ensure that operators are not overloaded? You want a language with an operator overloading feature, and I want a language with an operator-overloading-prevention feature. My preferred language lacks the feature you want, and your preferred language lacks the feature I want. The same language cannot give us both what we want, because what we want is contradictory. This is why we prefer different languages; some cater to your preferences and others to mine.
C++ destroyed the good will here by simultaneously insisting that you're only supposed to use this feature to give types their natural operators (makes sense) and then inventing implausible new "natural" operators so that Bjarne can show off his new toy with the I/O streams.

I actually don't like Rust's choice to implement + for Strings but most people seem to accept that, however C++ goes ludicrously far beyond "I don't like it but some people do" and straight off the cliff into "Nobody thinks that's OK" leaving you to wonder why there was effort to implement this bad idea. For example C++ can overload the short-circuiting boolean operators... but the overloaded versions don't short circuit. So now you've made things dramatically worse!

Note that it's not that Zig is opposed to (user-controlled) operator overloading; it's opposed to (user-controlled) overloading of all symbols: The resolution of `foo` in `foo(x)` should not depend on the type of `x`. The issue is not the operators but the overloading, and Zig wants to prevent (user-controlled) overloading of any kind. This makes some things less convenient and other things more convenient.
> The resolution of `foo` in `foo(x)` should not depend on the type of `x`

This depends on how you're squinting at this word "resolution".

Remember on a modern CPU an XOR R1 R1 does not result in an ALU operation, the decoder understands this idiom and just renames a zero'd register as R1, whereas of course it can't do that for say XOR R2 R3 because that's an actual XOR operation. So if "resolution" means "exactly what happens on the CPU" apparently there is no such facility provided even in assembler.

So apparently we mean only that it should have, in some sense, the same effect. I think the fact Rust is OK with

  assert!("Goose".contains('o'))
  assert!("Goose".contains("Goo"))
  assert!("Goose".contains(&['a', 'e', 'i', 'o', 'u']))
.. meets this criterion, whereas presumably you do not agree.
It's not about okay or not okay. Zig is designed to prevent any user code from being implicitly called, or for the resolution of user code to be done implicitly. It's not about what the CPU does internally, but whether you're able to tell, from reading the code of a single subroutine, which operations could be done, whether stack frames can be created etc.. This has pros and cons, and for some people the pros outweigh the cons and for others, the other way around, and that's why different programming languages need to prioritise different things when they target different users. Just as Rust clearly isn't supposed to be best for all uses, neither is Zig, or any other language for that matter. Every language is meant to appeal to some and not others.
Many people are against operator overloading, imo my only issue with C++ operator overloading is that you're allowed to overload the the assignment operator. From what I can see this is the root of many issues
I’ve also experienced some unnecessary shenanigans related to blurring the distinction between primitive operations, and stuff that happens dynamically at run time such as method calls.

For a somewhat different example of the same general idea, look at how Java handles primitives and their boxed counterparts. = on two ints always compares their value. = on two Integers compares their pointers. But it uses flyweight instances for values up to 256, so in Java, whether two Integers with the same numeric value are equal according to the = operator depends on what that value is.

Then throw autoboxing and generics into the mix, and it suddenly becomes very easy to do refactorings that work fine in the unit tests (which tend to use small numbers) but fails in confusing ways in production.

This isn’t an example of operator overloading, of course. But I hope it more simply illustrates why, at least in certain problem domains, there’s value in being able to visually tell when surprising runtime shenanigans are and are not possible. And also to make it impossible to cross that boundary without touching all code that falls within the blast radius of that change.

> But it uses flyweight instances for values up to 256, so in Java, whether two Integers with the same numeric value are equal according to the = operator depends on what that value is. ...

I believe Java caches Integer objects for values -128..+128, not 256. But that may be an implementation detail, and not something to count on.

No, you’re right. I misremembered.
> No, you’re right. I misremembered.

We both misremembered. I found where this is documented and the range is -128..127 inclusive: <https://docs.oracle.com/en/java/javase/27/docs/api/java.base...>

And since java 28's value types, == will work identically for all Integers, finally.
Note that value types will still be a "preview" feature in Java 28.

I'm looking forward to structured concurrency in Java 28. I already thought of a title for my article "Java Concurrency - Past, Present, and Futures".

In functional programming languages basically any unicode character can be used as function name, those with overloading issues in C++ better never come close to FP.
overloading the comma is also a special flavor. everyone should try it once.
Is there a way to support varying the meaning of "+" etc without introducing a lot of complexity? I suppose if Zig had nested functions, and the ability to define a nested function called "+", then you could have name shadowing instead of "overloading".

OCaml basically gives you operator overloading this way without actually doing overloading. I'm wondering why we can't have these OCaml-isms in other languages - without needing to use OCaml - which sadly comes with other commitments.

I always thought custom infix operators would be easy and basically what people want, e.g:

    const @<+> = @import("op.zig").special_add;

    const c = (a <+> b);
    //syntactic sugar for @<+>(a, b)
please no
Yes! And exceptions and inheritance and RTTI too. Bring back all the mistakes! Let's party like it's c++99