Blog no. 01
Introduction
So recently I watched the YouTube videos of Andrew Kelly (link-1, link-2) and became a fan of zig. I tried the ziglings exercises and loved the language, and now wants to get my hands dirty with zig. Thanks to friend and mentor Mr. Praseed Pai I have a set of simple C/C++ programs here (GNULinux.pdf) that I can rewrite in zig to learn. It covers simple but critical topics elegantly like going through environment variables, command line arguments, pipes, IPC etc and I think I'll enjoy this. As I'm going though this, I chose to share my journey with you. Hope you will enjoy it as me.
Prerequisites before reading this blog:
- My goal is to share some zig programs with you so that you also can get your hands dirty with zig. I will not be covering what zig is and what it is trying to achieve nor what it is trying to do different from c/rust/go. You must watch Mr. Kelly's talks and interviews for understanding this. I strongly believe that receiving information from the source is better than receiving it through the grapevine.
- Ziglings
- Knowledge about how native programming differs from cross-platform programming using C#/Java/Python.
- A little bit of exposure to C, enough to understand the interop programs that are going to come.
- Look up what C ABI is if you don't know what that is. (I did spell it correctly)
- You have zig compiler installed in your environment and is available in PATH
Program 01 : 3 ways of doing Hello, world!
There are three ways to do hello world in zig and let me explain. First, the program.
// helloworld.zig
const std = @import("std");
pub fn main(init: std.process.Init) !void {
// debug print. this writes to standard error, not standard out
std.debug.print("Hello, World! This is written using debug.print.\n", .{});
// writing to standard out without buffer
try std.Io.File.writeStreamingAll(.stdout(), init.io, "Hello, World! This is written using writeStreamingAll\n");
// writing to standard out with buffer (recommended approach)
// step 1: create a buffer array to hold string data.
var buffer: [1024]u8 = undefined;
// step 2: call the Writer.init method and pass in init.io.
var file_writer = std.Io.File.Writer.init(.stdout(), init.io, &buffer);
// step 3: strip type and take the interface so we have the option to
// write to anything including sockets or files and not just stdout.
var stdout_writer = &file_writer.interface;
// step 4: use the print method to print
try stdout_writer.print("Hello, World! This is written using Writer.print\n", .{});
// step 5: finally, before exiting, make sure you flush the buffer to screen
try stdout_writer.flush();
}
Lets run the program now. I'm using windows but the commands are same for all platforms.
C:/learn_zig>zig run helloworld.zig
This will run the program in debug mode. Now let's see how to build executable.
C:/learn_zig>zig build-exe -O ReleaseSafe helloworld.zig
Thanks for reading.
Top comments (0)