Style Guide

These coding conventions are not enforced by the compiler, but they are shipped in this documentation along with the compiler in order to provide a point of reference, should anyone wish to point to an authority on agreed upon Zig coding style.

Whitespace

  • 4 space indentation
  • Open braces on same line, unless you need to wrap.
  • If a list of things is longer than 2, put each item on its own line and exercise the ability to put an extra comma at the end.
  • Line length: aim for 100; use common sense.

Names

Roughly speaking: camelCaseFunctionName, TitleCaseTypeName, snake_case_variable_name. More precisely:

  • If x is a type then x should be TitleCase, unless it is a struct with 0 fields and is never meant to be instantiated, in which case it is considered to be a "namespace" and uses snake_case.
  • If x is callable, and x's return type is type, then x should be TitleCase.
  • If x is otherwise callable, then x should be camelCase.
  • Otherwise, x should be snake_case.

Acronyms, initialisms, proper nouns, or any other word that has capitalization rules in written English are subject to naming conventions just like any other word. Even acronyms that are only 2 letters long are subject to these conventions.

These are general rules of thumb; if it makes sense to do something different, do what makes sense. For example, if there is an established convention such as ENOENT, follow the established convention.

Examples

  1. const namespace_name = @import("dir_name/file_name.zig");
  2. var global_var: i32 = undefined;
  3. const const_name = 42;
  4. const primitive_type_alias = f32;
  5. const string_alias = []u8;
  6. const StructName = struct {
  7. field: i32,
  8. };
  9. const StructAlias = StructName;
  10. fn functionName(param_name: TypeName) void {
  11. var functionPointer = functionName;
  12. functionPointer();
  13. functionPointer = otherFunction;
  14. functionPointer();
  15. }
  16. const functionAlias = functionName;
  17. fn ListTemplateFunction(comptime ChildType: type, comptime fixed_size: usize) type {
  18. return List(ChildType, fixed_size);
  19. }
  20. fn ShortList(comptime T: type, comptime n: usize) type {
  21. return struct {
  22. field_name: [n]T,
  23. fn methodName() void {}
  24. };
  25. }
  26. // The word XML loses its casing when used in Zig identifiers.
  27. const xml_document =
  28. \\<?xml version="1.0" encoding="UTF-8"?>
  29. \\<document>
  30. \\</document>
  31. ;
  32. const XmlParser = struct {
  33. field: i32,
  34. };
  35. // The initials BE (Big Endian) are just another word in Zig identifier names.
  36. fn readU32Be() u32 {}

See the Zig Standard Library for more examples.