# Anonymous functions/lambdas

**URL:** <https://ziggit.dev/t/anonymous-functions-lambdas/1087>\
**Category:** Help\
**Tags:** language\
**Created:** [July 7, 2023, 12:26pm UTC](https://ziggit.dev/t/anonymous-functions-lambdas/1087 "2023-07-07T12:26:10Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![AndrewCodeDev](https://ziggit.dev/letter_avatar_proxy/v4/letter/a/278dde/32.png) [@AndrewCodeDev](https://ziggit.dev/u/AndrewCodeDev)\
**Post date:** [July 7, 2023, 3:26pm UTC](https://ziggit.dev/t/anonymous-functions-lambdas/1087/2 "2023-07-07T15:26:20Z")

</div>

Technically, yes you can but it’s not quite like a Java/C++ lambda (where there is a specific syntax for an anonymous function or closure).

Basically, because struct declarations are anonymous, you can declare a struct and return the member function from said struct. So for instance, in the HashMap implementation, here you can see they are creating a generic equality function:

```zig
pub fn getAutoEqlFn(comptime K: type, comptime Context: type) (fn (Context, K, K) bool) {
    return struct {
        fn eql(ctx: Context, a: K, b: K) bool {
            _ = ctx;
            return meta.eql(a, b);
        }
    }.eql;
}

```

Now this example is stateless so you’ll probably want to play around with stateful alternatives.

Basically Zig really, really does not like to allocate things if it isn’t absolutely necessary and a lot of closure implementations will take that liberty on your behalf - Zig won’t. Besides, you’d have to pass an allocator to the closure itself to give it the capability to allocate in the canonical sense. I don’t see closures making it into the language any time soon or even at all.

Furthermore, a lot of lambda-function like behavior can be achieved using meta programming. So for instance, I can create a comptime parameter of anytype “comptime foo: anytype” and then use that to generically dispatch on internals. I do _a lot_ of that here: [ZEIN/src/tensor\_ops.zig at main · andrewCodeDev/ZEIN · GitHub](https://github.com/andrewCodeDev/ZEIN/blob/main/src/tensor_ops.zig)

For instance, I am dispatching on different arithmetic functions generically for AVX instructions:

```zig
arithmeticDispatch(addGeneric, x, y, z); // addition dispatch
arithmeticDispatch(subGeneric, x, y, z); // subtraction dispatch
arithmeticDispatch(mulGeneric, x, y, z); // multiplication dispatch

```

The two approaches can be combined to make lambda-esque functionality but to answer your question, no - there is not a current specified and particularized lambda syntax.

---

_[View the full topic](https://ziggit.dev/t/anonymous-functions-lambdas/1087)._
