Zig Basic Types
A type describes the kind of value that a name holds. Zig has whole-number types, decimal-number types, and a true-or-false type.
Whole-number types hold positive and negative values
i32 values can be negative or positive. A u8 value stays between 0 and 255.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const age: i32 = 30;
const below: i32 = -5;
const level: u8 = 7;
try out.print("Age: {d}\n", .{age});
try out.print("Below: {d}\n", .{below});
try out.print("Level: {d}\n", .{level});
}Float types hold decimal numbers
An f64 value can keep a decimal part. A whole float value prints with no decimal part.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const pi: f64 = 3.14;
const whole: f32 = 3.0;
try out.print("Pi: {d}\n", .{pi});
try out.print("Whole: {d}\n", .{whole});
}A bool holds true or false
Each bool name below holds a different one of the two bool values. The prints show both.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const ready: bool = true;
const finished: bool = false;
try out.print("Ready: {}\n", .{ready});
try out.print("Finished: {}\n", .{finished});
}Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const count: i32 = 12;
const price: f64 = 9.5;
const code: u8 = 200;
const in_stock: bool = true;
try out.print("Count: {d}\n", .{count});
try out.print("Price: {d}\n", .{price});
try out.print("Code: {d}\n", .{code});
try out.print("In stock: {}\n", .{in_stock});
}Key points
- Type: a type says what kind of value a name can hold.
- i32: i32 holds whole numbers, both negative and positive.
- u8: u8 holds whole numbers from 0 to 255, with no negative values.
- f64: f64 holds numbers with a decimal part, such as 3.14.
- bool: bool holds one of two values, true or false.
- Annotation: writing a type after a name, after a colon, states that name's type.
In this example, count is an i32 and price is an f64, so one holds a whole number and the other holds a decimal number. code is a u8 that holds 200, and in_stock is a bool that holds true.
Note
a value that cannot fit in its type is a compile error in Zig.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which type holds the values true and false?