/

How to Create Your First Go Program

How to Create Your First Go Program

In this tutorial, we will guide you through creating your first Go program. By convention, the first program typically prints the “Hello, World!” string to the terminal. Let’s get started!

If you have a folder in your home directory where you keep all your coding projects and tests, go ahead and create a new folder called hello. Inside the hello folder, create a new file named hello.go (you can give it any name you prefer). Copy and paste the following code into the hello.go file:

1
2
3
4
5
6
7
package main

import "fmt"

func main() {
fmt.Println("Hello, World!")
}

Screen Shot 2022-07-28 at 12.17.14.png

Congratulations! You have created your first Go program.

Now, let’s analyze the code line by line to understand how it works:

1
package main

In Go, programs are organized into packages. Each .go file declares which package it belongs to. The main package is the entry point of the program and signifies an executable program.

1
import "fmt"

The import keyword is used to import packages in Go. The fmt package is a built-in package provided by Go that offers input/output utility functions. Go has a large standard library with numerous packages to help with common tasks like network connectivity, math, crypto, image processing, and filesystem access. You can explore the features provided by the fmt package in the official documentation.

1
2
3
func main() {

}

Here, we declare the main() function. In Go, a function is a named block of code that contains instructions. The main function is special because it is the starting point of the program. In our simple program, we only have one function, and execution begins with the main function and ends once it completes.

1
fmt.Println("Hello, World!")

This line is the content of our main function. Here, we call the Println() function from the fmt package that we previously imported. We pass the string “Hello, World!” as a parameter to the function. According to the documentation, Println() “formats according to a format specifier and writes to standard output”. Check out the documentation for more details and examples.

That’s it! Once the code inside the main function is executed, the program completes its execution.

By following this tutorial, you have successfully created your first Go program. Happy coding!

tags: [“Go programming”, “Go basics”, “Hello World program”]