• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

A Beginner's Guide to Enums and Error Sets in Zig

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Enums and error sets in Zig offer powerful ways to model states and failures with clarity and precision. In this tutorial, we’ll cover the basics, then walk through real-world uses of both types — and how they play nicely together.

Step 1: Defining Enums


Enums let you define a type with named values:


const Direction = enum {
North,
South,
East,
West,
};

You use them like this:


const dir = Direction.North;

Zig will guarantee at compile time that dir is one of the defined directions.

Step 2: Switching on Enums


Zig encourages exhaustive switching — the compiler checks for missing cases:


switch (dir) {
Direction.North => std.debug.print("Going up\n", .{}),
Direction.South => std.debug.print("Going down\n", .{}),
Direction.East => std.debug.print("Going right\n", .{}),
Direction.West => std.debug.print("Going left\n", .{}),
}

If you forget a case, Zig will complain — and that’s a good thing.

Step 3: Using Tagged Unions with Enums


You can pair an enum with associated data:


const Shape = union(enum) {
Circle: f32,
Square: f32,
};

Now Shape can either be a Circle with a radius, or a Square with a side length:


const s = Shape{ .Circle = 5.0 };

You can match and extract values:


switch (s) {
Shape.Circle => |r| std.debug.print("Circle radius: {}\n", .{r}),
Shape.Square => |s| std.debug.print("Square side: {}\n", .{s}),
}
Step 4: Error Sets


Error sets are custom error types. They're first-class citizens in Zig:


const MyError = error{
NotFound,
PermissionDenied,
};

You can use them as return types:


fn read() MyError!void {
return MyError.NotFound;
}

And handle them with catch, try, or a switch:


const result = read() catch |err| switch (err) {
MyError.NotFound => std.debug.print("Missing file\n", .{}),
MyError.PermissionDenied => std.debug.print("Access denied\n", .{}),
};
✅ Pros and ❌ Cons of Enums & Error Sets


✅ Pros:

  • ? Clear, type-safe control flow
  • ? Enforced exhaustiveness in switches
  • ? Custom error modeling with compiler support
  • ? Combine enums + unions for expressive state

❌ Cons:

  • ⚠ No implicit numeric values for enums (unlike C)
  • ? Switching can be verbose if not using else or _
  • ? Nested switches may become hard to read without care
Summary


Zig’s enums and error sets give you precise, predictable ways to model data and errors. Instead of relying on exceptions or raw integers, you build robust control flow with the compiler as your co-pilot. Learning how to use these together will level up both the clarity and safety of your codebase.

If this was helpful, you can also support me here:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

☕


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу