When it comes to learn new programming language, there is nothing gives like the satisfaction of writing your first "Hello, world!" program using that language. In this guide, we'll learn about Zig and write the process of building a "Hello, world!" program in Zig, a modern systems programming language (alternative to Rust) designed for performance, security, typed syntax and readability.
What is Zig?
Zig, created by Andrew Kelley, is a systems programming language that provide a balance of simplicity, performance, and safety. It has a C-like syntax and a strong focus on compile-time evaluation, which allows for efficient code generation and a high degree of type safety. It includes modern features such as algebraic data types, pattern matching, and comptime expressions, which can be great to write more expressive and concise code.
Writing the "Hello, world!" Program
Let's dive in and write a "Hello, world!" program. The program itself is quite simple and involves just a few lines of code.
Here is the code for "Hello, world!" program:
const std = @import("std");
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
try stdout.print("Hello, world!\n", .{});
}
Let's break program code line by line to see how it works.
Line 1: Importing the Standard Library
The first line of the program imports the standard library using the @import
keyword. In this case, we're importing the "std" library, which contains a wide variety of useful functions and types for working with standard input and output (I/O), files, strings, etc.
Line 2: Defining the main
Function
The next line defines the main
function using fn
keyword. The pub
keyword indicates that the function is public (can be called from outside the module). The !void
return type indicates that the function can throw an error but not a value.
Line 3: Getting the Standard Output Writer
The next line uses the getStdOut
function from std.io
module to obtain a Writer
object that writes to the stdout
stream. The writer
function is called on this object write data to the stdout stream.
Line 4: Printing the "Hello, world!" Message
The last line uses the print
function to print the "Hello, world!" message to the standard output stream. The first argument that specifies how to format the output simply "Hello, world!\n". The second argument is an empty tuple (.{}
).
That is how we get the output as "Hello World".
Conclusion
In conclusion, the "Hello, world!" program in Zig is a simple and straightforward way to get started with the language. We can quickly create a working program that demonstrates some of the language's key features.