MoKa Reads Cheatsheets

Variables and Data Types

By: Mustafif Khan

Language: Zig

Variables and Data Types

Var vs Const

In Zig we have two ways to create variables which differ from mutability, where var declares a mutable variable and const is immutable. Most cases will only require an immutable variable and its recommended to use const in most cases unless mutability is required, this improves security in your program and thus a key reason languages like Swift and Rust also provide abstractions like this.

Declaring a Variable

Now that we understand the difference between var and const, to declare a variable we can either declare its datatype explicitly (using the : operator) or implicitly. To look at the difference consider the following:

// syntax: <var/const> <ident>: <type> = <value>;

// Explicitly declared a floating point variable 
const float_num: f64 = 20.4; // data type f64

// Implicitly declared a floating point variable 
const float2 = 50.4; // data type comptime_float 

Variables cannot be left undeclared, if you do not have a known value when needing to declare the value you may use the undefined keyword.

Primitive Data Types

TypeC EquivalentDescription
i8int8_tSigned 8-bit integer
u8uint8_tUnsigned 8-bit integer
i16int16_tSigned 16-bit integer
u16uint16_tUnsigned 16-bit integer
i32int32_tSigned 32-bit integer
u32uint32_tUnsigned 32-bit integer
i64int64_tSigned 64-bit integer
u64uint64_tUnsigned 64-bit integer
i128__int128Signed 128-bit integer
u128unsigned __int128Unsigned 128-bit integer
isizeintptr_tSigned pointer-sized integer
usizeuintptr_t, size_tUnsigned pointer-sized integer
16_Float1616-bit floating point (10-bit mantissa) IEEE-754-2008 binary16
f32float32-bit floating point (23-bit mantissa) IEEE-754-2008 binary32
f64double64-bit floating point (52-bit mantissa) IEEE-754-2008 binary64
f80double80-bit floating point (64-bit mantissa) IEEE-754-2008 80-bit extended precision
f128_Float128128-bit floating point (112-bit mantissa) IEEE-754-2008 binary128
boolboolTrue or false
comptime_int(none)Only allowed for comptime-known values. The type of integer literals.
comptime_float(none)Only allowed for comptime-known values. The type of float literals.

These are provided by the official Zig Documentation, for more information check it out here.