Anonymous and Encapsulated Functions

for Zig 0.15.2 Buy

Anonymous and Encapsulated Functions

We have an anonymous function defined like this:

  // anonymous function only accessible within this scope

  const load_single = struct {

    fn _(o_me: *MachineGun, x_bullet: anytype) void {

      if (o_me.l_ammo.capacity == o_me.l_ammo.items.len)

        print("No more room\n", .{})

      else if (@TypeOf(x_bullet) == Proyectile)

        o_me.l_ammo.appendAssumeCapacity(x_bullet)

      else

        print("Can't shoot that!\n", .{});

    }

  }._;

Anonymous functions are those whose name doesn't matter because we only want to use what they do in a single place in the code. In Zig, to create an anonymous function, we use this form:


const result =  struct {

    fn function_name (  param: type,   … ,   paramN: typeN  ) return_type{

         // … function code

         return value;

    }

}.function_name( params …);  // extract the function and call it


We write a struct, define a function inside it, and call it immediately.

But in the previous example, we do something different:

  const load_single = struct {

   fn _(

   // ...

  }._;

Instead of calling it directly, we assign the extracted function to a constant. We've used the underscore _ as the internal name to keep things concise, but any other valid name can be used.

Why is this useful? Since Zig doesn’t allow defining functions inside other functions, we use this technique to encapsulate helper functions and avoid polluting the global scope with local code.

Instead of writing repeated anonymous functions like this:

  switch (@typeInfo(@TypeOf(x_ammo))) {

    .array => for (x_ammo) |o_bullet| struct {

        fn load_single(o_me: *MachineGun, x_bullet: anytype) void {

            // ...

        }

    }.load_single(self, o_bullet),

    else => struct {

        fn load_single(o_me: *MachineGun, x_bullet: anytype) void {

         // ...

    }.load_single(self, x_ammo),

  }

… we extract the function and avoid repeating code. Everything stays much cleaner.

anytype y T: type
Generic Recursion
© 2025 - 2026 Zen of Zig