Beginner's Guide to Go Programming

GolangGolangBeginner
Practice Now

Introduction

Now we are going to start learning Go officially. In this lab, we will learn some basic knowledge of Go and complete a Go program by ourselves.

Knowledge Points:

  • Standard output statement
  • Code structure
  • Running a program
  • Common functions in the fmt package

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/FunctionsandControlFlowGroup(["`Functions and Control Flow`"]) go/FunctionsandControlFlowGroup -.-> go/functions("`Functions`") subgraph Lab Skills go/functions -.-> lab-149062{{"`Beginner's Guide to Go Programming`"}} end

ðŸ’Ą First Go Program

First, right-click the sidebar to create the first code file helloWorld.go.

Image Description

Next, write the following code in the helloWorld.go file:

package main

import "fmt"

func main() {
    fmt.Println("hello, world")
}

Now let's try to print the newly written program. Enter the following command in the terminal to run the program:

go run helloWorld.go
image

In this way, a simple hello, world is printed. It feels fulfilling, right? Next, let's analyze the code and the meaning of the related operations line by line.

Program Structure and Syntax

In Go, the package is the most basic management unit. The beginning of each code file is a package declaration, which indicates which package the code in this file belongs to. For example, the first line is package main, which means that the helloWorld.go file belongs to the main package. If used in a project, there must be a main package. From here, we can see the similarity to the C language.

The second line import 'fmt' is used to import the packages that the program depends on. Go language provides a complete and powerful standard library, which allows us to quickly and efficiently build programs. This is one of the great advantages of Go. Here, we import the fmt package, which is a standard library used for format input and output. Other commonly used packages include string, net, etc., which will be explained in subsequent experiments.

Next comes the function declaration:

func main() {
}

In Go, all functions must start with func. For the sake of uniformity, Go also stipulates that { (left brace) must be at the end of the function definition line, rather than on a new line. However, there is no such restriction on } (right brace).

Try to modify the position of the braces as shown below, and then run it.

func main()
{
}

You will see a compilation error:

$ go run helloWorld.go
## command-line-arguments
./helloWorld.go:7:1: syntax error: unexpected semicolon or newline before {

Finally, the key statement of this code, which prints the hello, world string, is fmt.Println("hello, world"). This line of code calls the fmt package imported earlier and uses the Println function in the package to print the string. The fmt.Println function writes the string to the standard output and then adds a newline character at the end.

Running the Program

In previous learning, we learned that Go is a compiled and static language, but when printing hello, world, we found that it seemed to run directly from the source code file. This is because when executing the go run command, two commands are executed one after the other: first, the go build command compiles the source code file into an executable file, and then runs the compiled Go program.

In other words, the effect of the go run command is the same as compiling the program step by step (go build) and then calling the generated executable file. For example, the previous go run helloWorld.go is equivalent to the following commands:

## Compile the program
go build helloWorld.go
## Call the compiled executable file
./helloWorld

Now let's do a small test, greeting other Gophers using the program.

package main

import "fmt"

func main() {
 fmt.Println("hello Gopher.")
 fmt.Println("hello Gopher.")
 fmt.Println("hello Gopher.")
}

We need to create a new file helloGopher.go, and then replace the go run command with the go build command to output the following content in the terminal:

## Compile the program
go build helloGopher.go
## Call the compiled executable file
./helloGopher
hello Gopher.
hello Gopher.
hello Gopher.
âœĻ Check Solution and Practice

Common Functions in the fmt Package

In the first Go program, we used the Println() function in the fmt package for output.

The fmt package is one of the most commonly used packages in Go. It is usually used for formatting output or input. Let's introduce some of its most commonly used output functions through an example.

In Go, there are three types of output functions: Print() function, Println() function, and Printf() function, each with different functions. Let's explain them through an example.

Create a new fmt.go and enter the following code:

package main

import "fmt"

func main() {
    // Standard output
    fmt.Print("hello")
    fmt.Print("world")

    // Println adds a newline character after the standard output
    fmt.Println()
    fmt.Println("labex")

    // Printf provides formatted output
    fmt.Printf("%s\n", "Hangzhou")
}

First, we used the standard output Print() function to output hello and world separately. Although they are displayed on two lines, they are actually one line in the terminal. Print() directly outputs the string inside the function without line breaks or formatted outputs.

In the second part of the code, we used the Println function. The ln at the end stands for line, which means to output the string to the standard output and then add a newline character. We used an empty Println function to add a line break first, and then we used a standardized output to output the labex string and add a line break.

In the third part, we used the formatted output Printf function. The f at the end stands for format. We output the string type variable after the string placeholder %s. At the end, we also used \n for a line break.

Now let's summarize:

Function Standard Output Line Break Formatted Output
Print √ × ×
Println √ √ ×
Printf × × √

In addition to the commonly used output functions, the fmt package also includes a series of functions for input, error output, etc., which will be explained in later experiments.

Summary

So far, we have completed the first Go program in the Go language learning, and learned the basic structure of a Go program, how to write the source code file, and the commonly used output functions in the fmt package. I believe that all you Gophers have already learned it. Isn't it interesting? In the next experiment, we will delve into package management in Go.

Other Golang Tutorials you may like