Data Types and Variables in Zig

Just like in real life, we have different containers for different things. Let’s dive in!

Integers and Floating-Point Numbers

Integers are whole numbers without any decimal points. They can be positive, negative, or zero.

const age: i32 = 25; // 'age' is an integer variable storing the value 25.
const temperature: i16 = -10; // 'temperature' is an integer variable storing -10.

Floating-Point Numbers are numbers that can have decimal points. They can represent fractions.

const pi: f64 = 3.14159; // 'pi' is a floating-point constant storing pi (approximately 3.14).
const distance: f32 = 2.5; // 'distance' is a floating-point variable storing 2.5.

Imagine you’re a scientist. How would you use integers and floating-point numbers to represent measurements in your experiments?

Booleans and Characters

Booleans are like on-off switches. They can only be true or false.

const isRaining: bool = true; // 'isRaining' is a boolean variable storing 'true'.
const isSunny: bool = false; // 'isSunny' is a boolean variable storing 'false'.

Characters are single letters, numbers, or symbols.

const letter: char = 'A'; // 'letter' is a character variable storing 'A'.
const number: char = '7'; // 'number' is a character variable storing '7'.

Imagine you’re a wizard. How would you use booleans and characters to cast magical spells?

Strings and Bytes

Strings are sequences of characters. They’re like sentences or words.

const greeting: string = "Hello, Zig!"; // 'greeting' is a string constant.
var name: []const u8 = "Alice"; // 'name' is an array of bytes storing "Alice".

Bytes are the individual characters or elements that make up strings.

const firstLetter: u8 = 'H'; // 'firstLetter' is a byte storing the ASCII code for 'H'.

If you were writing a magical message, how would you use strings and bytes to make sure it’s just right?

Arrays and Slices

Arrays are like collections of items. They can hold multiple pieces of data.

const numbers: [4]i32 = [1, 2, 3, 4]; // 'numbers' is an array of 4 integers.
const colors: [3]string = ["red", "green", "blue"]; // 'colors' is an array of color names.

Slices are like a portion of an array. They allow us to work with a specific section.

const slice: []const u8 = "Zig".[]; // 'slice' is a slice of the string "Zig".

Imagine you’re a chef. How would you use arrays and slices to organize your ingredients and recipes?

So, let’s start practicing.

Need further assistance, paid dedicated one-to-one tutor, need assignments done or have a paid project in Zig?

Leave a Reply

Your email address will not be published. Required fields are marked *