Introduction to the

In this module, you will start using Go. You’ll learn about the history of Go and the main features of the programming language. Go will then be installed and configured on the workstation. Next, you’ll explore another way to use Go without having to install anything on your workstation. You’ll also learn how Go requires you to organize your code to help prevent problems when you need to develop complex applications.

At the end of the module, you create the first “Hello World!” with Go. Application, and then you can Go on to learn more about how to use Go to build the application.

Learning goals

In this module you will:

  • Install and configure Go on your local workstation.
  • Install and configure Visual Studio Code and the Go extension.
  • Browse the Go Playground.
  • Create your first Go app.

A prerequisite for

  • Familiar with general programming basics
  • Be familiar with at least one programming language
  • Be familiar with downloading and installing software from the Internet

What is Go?

Go is a programming language developed by Google and released as an open source project in 2009 by Robert Griesemer, Rob Pike, and Ken Thompson. Since then, Go has been used to develop other well-known technologies such as Docker, Kubernetes, Terraform, etc. But Go is also a universal language. The goal of the language is to make programmers expressive, efficient, and effective in writing reliable and powerful code.

Go was the programming language of the year in 2009 and 2016, according to the TIOBE index. Although Go reached a tipping point in 2016, it still retains a strong reputation. Since 2015, Go has also been named one of the most popular languages according to the annual Stack Overflow Developer survey.

Go has much in common with C in that it inherits many aspects of C syntax, control flow statements, basic data types, Pointers, and other elements. But Go is more than just the latest version of C. It borrows and ADAPTS ideas from other programming languages, while removing unnecessarily complex features. For example, some parts of the object-oriented programming paradigm are not fully implemented in Go. You’ll see why in the next few modules.

Go is well used in topics such as source code formats, banning unused code, no NEED for an IDE, preference for standard libraries over frameworks, and other ways to provide concurrent programming and error handling.

Go runs on Unix systems such as Linux and macOS, and also supports Windows.

The principle of the Go

To understand the reasons for some of the operations in Go, it’s important to understand the principles behind the programming language:

  • Go aims to keep things simple, doing more with fewer lines of code.
  • Concurrency is preferred, and functions can be run as lightweight threads.
  • Compile and execute fast, aiming to be as fast as C.
  • Go requires the cast to be explicit, or a compilation error will be raised.
  • Unused code is not a warning, but an error, and the code will not compile.
  • There is an official formatting that helps maintain consistency between projects.
  • Go does not work with frameworks because it prefers to use standard libraries.
  • Go ensures backward compatibility.
  • The Go license is fully open source.

Install the Go

Before you can start creating applications with Go, you need to set up your development environment.

If you don’t want to install Go locally, you can use Go Playground, a Web service that runs applications written in Go in a browser. This is a great choice if you want to run code examples quickly and easily. However, when building applications that require more complex code organization, it is recommended to set up the local environment.

Install Go on Windows

To install Go on Windows, download the Go installer from the Go Download page.

Step 1: Download the Go installer

In the “Selected Downloads” section of the Go Download page, select the “Microsoft Windows” option.

A window may appear prompting you to allow the file to be downloaded from Golang.org. If so, select Allow.

Step 2: Run the MSI Go installer

After you download the Go installer locally, you can start installing Go. To do this, double-click the.msi file and follow the instructions.

By default, the.msi file installs Go at C:\Go, and PATH C:\Go\bin should now be part of the $PATH environment variable.

Step 3: Verify that Go has been installed correctly

After Go distribution is configured, check whether Go works properly. To do this, open a new command prompt or PowerShell window and run the following command:

go version
Copy the code

Install Go on macOS

To install Go on macOS, use Homebrew or download the page from Go. You will find both methods on this page, but please choose only one.

Install Go using Homebrew

The easiest way to install Go is to use Homebrew.

Open the terminal prompt and run the following command:

brew update
brew install go
Copy the code

Homebrew installs go at /usr/local/go, where the PATH /usr/local/go/bin should now be part of the $PATH environment variable. You may need to reopen the terminal prompt to confirm that Go is installed correctly.

To confirm that Go is installed, run the following command:

go version
Copy the code

Install Go using the Go installer

Alternatively, you can install the latest version of Go by doing the following:

Step 1: Download the Go installer

In the “Selected Downloads” section of the Go Download page, select the “Apple macOS” option.

A window may appear prompting you to allow the file to be downloaded from Golang.org. If so, select Allow.

Step 2: Run the Go installer

After downloading the Go installer locally, you can begin the installation. Double-click the.pkg file and follow the instructions to install Go.

By default, the.pkg file installs go in /usr/local/go, and the PATH /usr/local/go/bin should now be part of the $PATH environment variable.

Step 3: Verify that Go has been installed correctly

When the installation is complete, open a new terminal prompt and run the following command:

go version
Copy the code

Install Go on Linux

To install Go on Linux, download the Go installer from the Go Download page. If for some reason you have installed Go and want to install the latest version, remove the existing version before continuing.

Step 1: Download the Go installer

In the “Selected Downloads” section of the Go Download page, select the “Linux” option.

A window may appear prompting you to allow the file to be downloaded from Golang.org. If so, select Allow.

Note: If 1.15.4 is not the latest version when reading this guide, you may need to change the version number in the command.

Alternatively, you can download the installer by running the following command at your terminal prompt:

Wget HTTP: / / https://golang.org/dl/go1.15.4.linux-amd64.tar.gzCopy the code

Step 2: Extract the Go installer

After you download the Go installer locally, you can start setting up Go on your workstation. Extract the installer at /usr/local/go and run the following command as root or through sudo:

tar -C /usr/local- XZF go1.15.4. Linux - amd64. Tar. GzCopy the code

The PATH /usr/local/go/bin needs to be added to the PATH environment variable. To make Go available system-wide, add the following command to the PATH environment variable. To make Go available system-wide, add the following command to the PATH environment variable. To make Go available system-wide, you can add the following command to either HOME/. Profile or /etc/profile:

export PATH=$PATH:/usr/local/go/bin
Copy the code

You need to close and reopen the terminal prompt to update the $PATH environment variable. Alternatively, you can force the update by running the following command:

source $HOME/.profile
Copy the code

Step 3: Verify that Go is installed correctly After configuring Go distribution, run the following command to verify that Go works properly:

go version
Copy the code

Details of the Go version installed on the workstation should be displayed.

Organizing code projects

Be sure to read this section carefully before proceeding.

Go differs from other programming languages in organizing project files. First, Go works under the concept of a workspace, where the application source code resides. In Go, all projects share the same workspace. However, starting with version 1.11, Go began to change this method. You don’t have to worry yet, because we’ll cover workspaces in the next module. For now, the Go workspace is located at $HOME/ Go, but you can set other locations for all projects if you want.

To define additional workspace locations, set the value to the $GOPATH environment variable. When you start creating more complex projects, you need to set a value for the environment variable to avoid future problems.

On macOS or Linux, you can configure your workspace by adding the following command to ~/.profile:

export GOPATH=$HOME/go
Copy the code

Then run the following command to update the environment variables:

source ~/.profile
Copy the code

In Windows, create a folder (such as C: Projects\Go) in which you will create all Go Projects. Open the PowerShell prompt and run the following command:

[Environment]::SetEnvironmentVariable("GOPATH"."C:\Projects\Go"."User")
Copy the code

In Go, you can get the workspace location for future reference by printing the value of the $GOPATH environment variable. Alternatively, you can obtain go-related environment variables by running the following command:

go env
Copy the code

In the Go workspace, you can find the following folders:

  • Bin: contains executable files in the application.
  • SRC: includes all the application source code that resides on the workstation.
  • PKG: Contains a compiled version of the available libraries. The compiler can link these libraries without having to recompile them.

For example, the workstation folder structure tree looks like this:

bin/
    hello                          
    coolapp                        
pkg/
    github.com/gorilla/
        mux.a 
src/
    github.com/golang/example/
        .git/                      
    hello/
        hello.go
Copy the code

We’ll return to this topic in the next module and discuss what to do when you need or want to maintain a project outside of the $GOPATH environment.

You can also delve into this topic by visiting the official documentation site on how to write Go code.

Exercise – Browse the Go Playground

As we mentioned earlier in this module, if you don’t want to install Go on your local workstation yet, you can use Go Playground, which compiles and runs Go code in a sandbox environment. This tool is often used to share snippets of code with other developers when sharing solutions in forums.

Please note that Go Playground has some restrictions that may affect the learning journey. Such as:

  • Keyboard input is not supported.
  • Random numbers are deterministic.
  • Time is constant. You get the same value every time.

To start using Go Playground, select the Run button.

You can continue to use this site for learning at any time, but it is strongly recommended that you install Go locally and use an integrated development environment (IDE) to increase your development efficiency.

Exercise – “Hello World”

Step 1: Create a new folder for the project and a Go file Create a new directory called “HelloWorld” and create a new file called “main.go” in it. Open the “main.go” file and type the following code:

package main

import "fmt"

func main(a) {
    fmt.Println("Hello World!")}Copy the code

Save the file.

Step 2: Executing the program Now you can run the program. Run the following command on the terminal:

go run main.go
Copy the code

You should see the following output:

Hello World!
Copy the code

The “go run” command performs two tasks. First, it compiles the application and, if all goes well, executes it. Executable files can be generated by simply running the following command:

go build main.go
Copy the code

When the preceding command completes, it generates an executable application that you can run at any time without further processing. Now, the project should look like this:

helloworld/                     
  main
  main.go
Copy the code

A file name without a file extension (or.exe on Windows) is an executable file that can be used to run the program. At development time, the go run command is used. But when you generate binaries for your application, you use the Go build command and deploy the binary executable to the appropriate environment.

What did you just write with Go? Now that you’ve created your first Go application and made sure it compiles and runs, Go through the code you just wrote line by line.

Let’s start with the following line:

package main
Copy the code

In this way, the applications to be created in Go are defined as executables (files that can be run). The “Hello, World!” Applications are part of the main package. A package is a commonly used set of source code files. Every executable application has this first line, even if the project or file has a different name.

We’ll delve into this topic in the next module, but for now, note that each executable should be part of the main package.

Challenge: To confirm what you just read, change the package name in the first line and try running the program. What’s going on? Do you see “Hello World! Output or any binary executable file?

Now, let’s discuss the following lines:

import "fmt"
Copy the code

The import statement makes the program accessible from other code in other packages. In this case, the FMT is the standard library package, documented on the official Go documentation site.

You need this import statement because you will use the functions in this package to print messages to the screen later in the program. You can include as many imports as you want or need in your program. However, Go is very idiomatic in this regard. If you import packages without using statements, the application will not compile.

Challenge: To confirm what you just read, include another import, such as Math or IO. What’s going on?

Let’s discuss the following blocks:

func main(a) {
   fmt.Println("Hello World!")}Copy the code

Func statements are reserved words used to declare functions. Now, let’s discuss why this function is called main. The main function is the starting point of the program. Therefore, there can only be one main function (the one defined in the first line) in the entire package. In this function, you call the Println function in the FMT package and send the text message you want to see on the screen.

There is more information about functions, which we will cover in the next module.

conclusion

The goals in this module are to guide you through the initial steps of using Go, setting up a work environment to create more projects with Go, and quickly writing programs to Go standards. By creating a typical Hello World! You learned how to compile and run programs written in Go.

To avoid future problems, remember that all projects in Go share the same workspace on your computer. It is recommended to create all projects in the $GOPATH/ SRC directory. However, there may be times when you need to create projects in other locations. In the next module, we will discuss how to store project code elsewhere.

Finally, you see the difference between the Go build and Go Run commands. The go build command compiles the program and, if there are no errors, produces a binary executable that can be run without go. This command is typically used to generate application binaries for deploying applications to different environments. The go run command compiles and executes the application without generating binaries. This command is used when the application is developed and tested locally.

The next section,

(2) Know how to use packages, variables, and functions

Article source: www.sdk.cn/details/5Oo…