Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Writing Your First Go Program

1. Introduction

Welcome to the world of Go programming! Go, also known as Golang, is an open-source programming language developed by Google. It's known for its simplicity, efficiency, and strong support for concurrent programming. In this tutorial, we will guide you through writing your very first Go program, from setting up your environment to running your code.

2. Setting Up the Environment

Before we write any Go code, we need to set up our development environment.

Step 1: Download and install Go from the official website: https://golang.org/dl/

Step 2: Verify your installation by opening a terminal and typing the following command:

go version

You should see output similar to:

go version go1.16.3 darwin/amd64

3. Writing Your First Program

Now that we have Go installed, let's write our first program. We will create a simple "Hello, World!" program.

Step 1: Open your favorite text editor and create a new file named main.go.

Step 2: Enter the following code into the file:

package main

import "fmt"

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

Let's break down this code:

  • package main: This line defines the package name. In Go, every program must belong to a package, and the main package is the entry point of the program.
  • import "fmt": This line imports the fmt package, which contains functions for formatting text, including printing to the console.
  • func main(): This defines the main function, which is the entry point of the program. The code inside this function will be executed when the program runs.
  • fmt.Println("Hello, World!"): This line prints "Hello, World!" to the console.

4. Running Your Program

Once you have written your code, it's time to run it.

Step 1: Open a terminal and navigate to the directory where you saved main.go.

Step 2: Run the following command to execute your program:

go run main.go

You should see the following output:

Hello, World!

Congratulations! You've just written and executed your first Go program.

5. Compiling Your Program

In addition to running your program, you can also compile it into an executable file.

Step 1: Run the following command to compile your program:

go build main.go

This will generate an executable file named main (or main.exe on Windows).

Step 2: Run the executable file:

./main

You should see the same output:

Hello, World!

6. Conclusion

In this tutorial, we have walked you through writing, running, and compiling your first Go program. You've learned about the basic structure of a Go program and how to use the fmt package to print text to the console.

Go is a powerful language with many features to explore. We encourage you to continue learning and experimenting with Go. Happy coding!