Golang by Example

Logo

Hello World

This is the source code of the traditional Hello World program.

fmt.Println is a function from the fmt package that prints text to the console. The text to be printed is passed as an argument to the function. In this case, we are printing "Hello, World!".

A binary can be compiled from this code using the go build command. The resulting binary can be executed to run the program.

$ go build hello-world.go

Go binary will produce an executable file named hello-world (or hello-world.exe on Windows). You can run the program by executing the binary:

$ ./hello-world
Hello, World!

In the more simpler manner, you can run the code directly using the go run command:

$ go run hello-world.go
Hello, World!

Expressions

A Go program is (mostly) made up of a series of statements.

func main() {
    // statement
    // statement
    // statement
}

A statement is a complete instruction that performs an action. In Go, statements are typically written in the main function, which is the entry point of the program. Each statement is separated by a semicolon (;), but in Go, semicolons are optional and are automatically inserted by the compiler at the end of each line. In the example above, the main function contains a single statement that prints "Hello, World!" to the console. You can add more statements to the main function to perform additional actions.

func main() {
    fmt.Println("Hello, World!")
    fmt.Println("I am a Gopher!")
}

Now your turn!

You can edit the code in the editor above. Try adding the text to be printed to the console. For example, you can add "Welcome to Go programming!".

Hello, World!
I am a Gopher!
Welcome to Go programming!

Operations

You can perform operations upon values in Go. For example, you can use the + operator to concatenate strings or add numbers. You can also use the -, *, and / operators to perform subtraction, multiplication, and division, respectively. Here are most common operators in Go that you'll use frequently:

💡 Quiz
How do you check if a value is an odd or even number in Go?

Comments

In the Hello World code above, you might notice that it contains comments. Any program requires comments. Comments are ignored by the compiler and are used to document the code. In Go, comments can be written using // for single-line comments or /* ... */ for multi-line comments.

// This is a single-line comment
/* This is a multi-line comment
   that spans multiple lines */

Packages's comment

In Go, each package can have its own comment, which is typically placed at the top of the package file. This comment should provide a brief overview of the package's purpose and functionality.

// Package path provides functions for manipulating and processing
// paths that use forward slashes as separators.
//
// This package is intended for handling URL-like paths with forward
// slashes only. It does not support Windows-style paths containing
// drive letters or backslashes. For operating system file paths,
// use the [path/filepath] package instead.
package path

Square brackets in the [path/filepath] package are used to refer to other packages in the Go standard library. This is a common convention in Go documentation to provide links to related packages or functions.

Command's comment

In Go, commands can also have comments. These comments are typically placed at the top of the command file and provide a brief overview of the command's purpose and functionality.

/*
Hello world is a simple program that prints "Hello, World!" to the console.
This is a simple program that demonstrates the basic structure of a Go program.

Usage: ./hello-world
*/
package main

The beginning of the command file contains a comment block that describes the command's purpose and usage. This comment block is typically enclosed in /* ... */ and provides information about how to use the command. The comment block may also include examples of how to run the command and any command-line flags or options that are available. go doc and pkgsite will display this comment block when you run the command or view the package documentation. For example,

$ go doc hello-world
Hello world is a simple program that prints "Hello, World!" to the console.
This is a simple program that demonstrates the basic structure of a Go program.

Usage: ./hello-world

Type's comment

In Go, types can also have comments. These comments are typically placed immediately before the type definition and provide a brief overview of the type's purpose and functionality. Please don't bother about the struct now, it just for demonstration. We will cover it in the next chapter.

// Person represents a person with a name and age.
type Person struct {
    Name string // The name of the person
    Age  int    // The age of the person
}

The comment block describes the purpose of the Person type and its fields. The field comments provide additional information about each field's purpose and usage.

Function's comment

Functions in Go can also have comments. Again, don't be intimidated by the syntax. We will cover it in the next chapter. These comments are typically placed immediately before the function definition and provide a brief overview of the function's purpose and functionality.

// Add adds two integers and returns the result.
func Add(a int, b int) int {
    return a + b
}

The comment block describes the purpose of the Add function and its parameters. The parameter comments provide additional information about each parameter's purpose and usage.

Formatted print

Printing is one of the most common tasks in programming. In Go, you can use the fmt package to format and print text to the console. The fmt package provides several functions for formatted printing, including Print, Println, and Printf.

Print syntax is used to print text to the console without a newline at the end. The only difference between Print and Println is that Println adds a newline at the end of the text.

As for, the Printf function allows you to format the text using placeholders, such as %s for strings and %d for integers. The Sprintf function formats the text and returns it as a string without printing it to the console. Here are some placeholders you can use with Printf and Sprintf:

PlaceholderDescription
%sString
%dDecimal integer
%fFloating-point number
%tBoolean value (true/false)
%vDefault format for any value
%TType of the value
%xHexadecimal representation
%oOctal representation
%bBinary representation
%cCharacter representation
%pPointer representation
%qQuoted string representation
%UUnicode format
%eScientific notation
%EScientific notation (uppercase)
%gShortest representation
%GShortest representation (uppercase)
%nNumber of bytes written
%mError message
%wError wrapping

Not quite a Hello World, is it? 😮‍💨

Things are excalated quickly, right? But don't worry, we will cover all these topics in the upcoming chapters. For now, just remember that fmt package is used to format and print text to the console. You can use Print, Println, and Printf functions to print text with different formatting options.


Table of contents

Hello World - Begin with the classic Hello World program
Primitives - Learn about the basic data types in Go
Flow Control - Controlling the flow of your program
Struct - All about struct
Functions - Define and call functions
Methods and Interfaces - Methods and interfaces in Go
Error Handling - Handling errors idiomatically
Concurrency - Goroutines and channels
Anti Patterns - Anti patterns in Go
Libraries - Standard library and third-party libraries
Testing - Writing unit tests with `go test`
Benchmarking - Performance benchmarks
Containerization - Dockerize your Go app
What's Next? - Explore the next steps in your Golang journey


Share to: