0Pricing
Zig Academy · Lesson

Enum Methods and Backing Integers

Add behavior and control representation.

Enums Can Have Behavior

An enum is a real type, so it can hold methods. You declare functions inside the enum body, right next to the value names.

A Method on an Enum

Write a function inside the enum and take self as the first parameter. It works just like a method on a struct.

const Color = enum { red, green, fn isRed(self: Color) bool { return self == .red; } };

All lessons in this course

  1. Enums for a Fixed Set of Values
  2. Unions That Hold One of Many Types
  3. Tagged Unions and switch
  4. Enum Methods and Backing Integers
← Back to Zig Academy