01 Basics Write Your First Go Program

01 Basics - Write Your First Go Program #

Starting from this lesson, I will introduce you to the world of Go language. I will explain various concepts of Go language in simple and easy-to-understand language, so that you can learn from scratch and gradually delve into its world. Whether you have previously encountered Go language or not, you can benefit from this column.

Now, let me introduce you to Go language by using a classic example of “Hello World” to understand how it works.

Hello, World #

If you have learned C language, you should be familiar with this classic example. Through this example, I will first give you a general understanding of the core concepts of Go language, so that you have an overall impression of Go language code. It is shown as follows:

ch01/main.go

package main

import "fmt"

func main() {
    fmt.Println("Hello, 世界")
}

These five lines of code constitute a complete Go program, isn’t it very simple? Now I will run this code to see the output. To do so, open the terminal and enter the following command, then press Enter.

$ go run ch01/main.go

Hello, 世界

The command I entered, go run ch01/main.go, and the “Hello, 世界” you see after pressing Enter are the results output by the Go program.

The go in the code is a command provided by the Go development toolkit, and it is an executable command just like the commonly used ls command. It can help you run Go language code, compile it, and generate executable binary files, etc.

In this case, run is a subcommand of the go command, which means running Go language code. Finally, ch01/main.go is the file containing the Go language code I wrote. In other words, the entire go run ch01/main.go means running the Go language code in ch01/main.go.

Program Structure Analysis #

To make a Go language program run successfully, you only need two core parts: package main and main() function. package main represents that the ch01/main.go file belongs to which package. package is a keyword in Go language used to declare a package, and main is the package name to be declared. In Go language, the main package is a special package, which means that your Go language project is an executable application, rather than a library referenced by other projects.

The import "fmt" on the second line is to import the fmt package. import is a keyword in Go language that means importing a package. Here, I import the fmt package for the purpose of using it, which will be explained below.

The func main() on the third line defines a function. func is a keyword in Go language that means defining a function or method, and main is the function name. The empty parentheses () indicate that this main function does not accept any parameters. In Go language, the main function is a special function, it represents the entry point of the entire program. When the program is running, it will first call the main function, and then call other functions through the main function to achieve the goal of implementing project business requirements.

The fmt.Println("Hello, 世界") on the fourth line prints the text “Hello, 世界” using the Println function from the fmt package. fmt is the package that was imported just now. To use a package, it must be imported first. Println is a function belonging to the fmt package, and here I need it to print the text “Hello, 世界”.

The curly brace } on the fifth line indicates the end of the main function body. Now the entire code snippet has been analyzed, and you can see the output of the “Hello, 世界” result by running it.

From the analysis above, Go language code is very concise and complete, and it only needs core concepts like package, import, func main to implement. In the lessons that follow, I will also explain how to use variables, how to define custom functions, etc., but let’s now take a look at how to set up the Go language development environment so that the above Go language code can be run and get the whole program up and running.

Setting up Go language environment #

To set up the Go language development environment, you need to download the Go language development package first. You can download it from the official website https://golang.org/dl/ and https://golang.google.cn/dl/ (the first link is for the international website, the second link is for the Chinese website. If the first link is inaccessible, you can download it from the second link).

When downloading, you can choose the corresponding package according to your operating system, such as Windows, macOS, or Linux, as shown in the following figure:

go_sdk_download.png

Installing on Windows using MSI #

The MSI installation method is relatively simple and recommended for Windows systems. Most operating systems today are 64-bit, so you can choose go1.15.windows-amd64.msi for downloading. If your operating system is 32-bit, choose go1.15.windows-386.msi for downloading.

After downloading, double-click on the MSI installation file and follow the prompts to install. By default, the Go language development toolkit will be installed in the c:\Go directory, but you can choose your desired installation directory during the installation process.

Assuming you install it in the c:\Go directory, the installer will automatically add c:\Go\bin to your PATH environment variable. If it’s not added, you can manually add it through System → Control Panel → Advanced → Environment Variables.

Installing on Linux #

Linux systems also have 32-bit and 64-bit versions. You can choose the corresponding compressed package for your Linux operating system, which are go1.15.linux-386.tar.gz and go1.15.linux-amd64.tar.gz respectively.

After successfully downloading, you need to unpack it first. Assuming you downloaded go1.15.linux-amd64.tar.gz, you can use the following command in the terminal to unpack it:

sudo tar -C /usr/local -xzf go1.15.linux-amd64.tar.gz

Press Enter after entering the command, then enter your computer password to unpack it to the /usr/local directory. Then add /usr/local/go/bin to the PATH environment variable, and you can start using the Go language development toolkit.

Add the following snippet to the /etc/profile or $HOME/.profile file, and save and exit to successfully add the environment variable.

export PATH=$PATH:/usr/local/go/bin

Installing on macOS #

If your operating system is macOS, you can use the PKG installation package. After downloading go1.15.darwin-amd64.pkg, double-click it and follow the prompts to install. After successful installation, the path /usr/local/go/bin should have been added to the PATH environment variable. If not, you can manually add it. Similar to the Linux method mentioned above, add the following content to the /etc/profile or $HOME/.profile file and save it.

export PATH=$PATH:/usr/local/go/bin

Testing the installation #

After successful installation of the above steps, you can open the terminal or command prompt and enter go version to verify if the Go language development toolkit has been installed successfully. If successful, it will print the version of Go language and system information as shown below:

$ go version

go version go1.15 darwin/amd64

Setting environment variables #

After installing the Go programming language development kit, the development environment is not completely set up yet because there are still two important environment variables that need to be set: GOPATH and GOBIN.

  • GOPATH: represents the working directory of Go language projects. Before Go Module mode, it was very important, and now it is mainly used to store projects obtained using the “go get” command.
  • GOBIN: represents the installation directory of compiled Go programs. For example, when using the “go install” command, the generated Go program will be installed in the GOBIN directory for use in the terminal.

Assuming the working directory is /Users/flysnow/go, you need to set the GOPATH environment variable to /Users/flysnow/go and the GOBIN environment variable to $GOPATH/bin.

On Linux and macOS, add the following content to /etc/profile or $HOME/.profile and save the file.

export GOPATH=/Users/flysnow/go

export GOBIN=$GOPATH/bin

On Windows, add these two environment variables through the Control Panel -> Advanced -> Environment Variables option.

Project Structure #

Using Go Modules, you can create your Go language projects anywhere. In this column, I will demonstrate Go language examples using this method. Now, let’s have a rough understanding of the Go Module project structure. I will provide a detailed introduction to Go Modules in the following lessons.

Assuming your project is located at /Users/flysnow/git/gotour, open the terminal and enter the following command to switch to that directory:

$ cd /Users/flysnow/git/gotour

Then, execute the following command to create a Go Module project:

$ go mod init

After successfully executing this command, a go.mod file will be generated. Then, create a main.go file in the current directory. The entire project directory structure will be as follows:

gotour
├── go.mod
├── lib
└── main.go

In this structure, main.go is the entry file of the entire project and contains the main function. The lib directory is a submodule of the project. Depending on the project requirements, you can create many directories as submodules or continue to nest submodules within submodules.

Compilation and Deployment #

Once your project is completed, you can compile it into an executable file and also publish it to the $GOBIN directory for use in the terminal. Let’s take “Hello World” as an example. In the project root directory, enter the following command to compile an executable file:

$ go build ./ch01/main.go

After entering this command, a “main” executable file will be generated in the current directory. Now, let’s test if it works:

$ ./main
Hello, 世界

If “Hello, 世界” is printed successfully, it means the program has been successfully generated.

The executable file generated above is in the current directory, but you can also install it in the $GOBIN directory or any other location, as shown below:

$ go install ./ch01/main.go

Just use the “go install” command. Now, at any time you open the terminal and enter “main”, “Hello, 世界” will be printed. Isn’t it convenient?

Cross-platform Compilation #

Another powerful feature of the Go programming language development kit is cross-platform compilation. What does cross-platform compilation mean? It means that while developing on macOS, you can compile executable programs for platforms such as Linux and Windows, allowing your programs to run on these platforms. In other words, you can choose the operating system you like for development and compile it into executable programs for the target platform through cross-platform compilation.

The Go programming language kit uses two environment variables, GOOS and GOARCH, to control cross-platform compilation.

  • GOOS: represents the target operating system to compile for, such as Linux, Windows, Darwin, and more.
  • GOARCH: represents the target processor architecture to compile for, such as 386, AMD64, ARM64, and more.

By combining different values for GOOS and GOARCH, you can compile different executable programs. For example, if your current operating system is macOS AMD64 and you want to compile a Linux AMD64 executable program, simply execute the “go build” command as shown below:

$ GOOS=linux GOARCH=amd64 go build ./ch01/main.go

For more combinations of GOOS and GOARCH, please refer to the official documentation section “(GOOS and) GOARCH”.

Having a good editor can greatly improve development efficiency. Here, I recommend two popular editors.

The first one is Visual Studio Code with the Go extension plugin, which allows you to develop efficiently. You can download and use it from the official website https://code.visualstudio.com/.

The second one is Goland, produced by JetBrains, a well-known IDE company. All plugins are already integrated, making it easier to use. It also has powerful features suitable for both beginners and experienced developers. You can download and use it from the official website https://www.jetbrains.com/go/.

Summary #

In this lesson, you learned how to write your first Go program and set up the Go development environment. You also created a Go project and downloaded an IDE. Now, I will assign you a small task:

Modify the code of the “Hello World” example to print your own name.