Skip to main content
Version: Zig 0.14.0 (dev)

Assignment

Value assignment has the following syntax: (const|var) identifier[: type] = value.

  • const indicates that identifier is a constant that stores an immutable value.
  • var indicates that identifier is a variable that stores a mutable value.
  • : type is a type annotation for identifier, and may be omitted if the data type of value can be inferred.
const constant: i32 = 5; // signed 32-bit constant
var variable: u32 = 5000; // unsigned 32-bit variable

// @as performs an explicit type coercion
const inferred_constant = @as(i32, 5);
var inferred_variable = @as(u32, 5000);

Constants and variables must have a value. If no known value can be given, the undefined value, which coerces to any type, may be used as long as a type annotation is provided.

const a: i32 = undefined;
var b: u32 = undefined;
Coming from JavaScript?

If you're familiar with JavaScript, you might be used to using undefined as a way to represent a variable that hasn't been initialised, or to represent an absense of value.

However in Zig, using undefined like this is a bad idea as undefined works very differently. In JavaScript, values can be checked for being undefined, whereas in Zig, an undefined value is impossible to detect. Usage of undefined values is not safe. Zig's undefined is "undefined" as in "undefined behaviour", and should not be used as a stand-in for an optional.

Need optionals? These are covered later.

Where possible, const values are preferred over var values.