Beginner's Guide to Go Programming

GolangGolangIntermediate
Practice Now

Introduction

In this lab, we will officially start learning Go programming. We'll cover basic concepts and complete a simple Go program 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(("Golang")) -.-> go/FunctionsandControlFlowGroup(["Functions and Control Flow"]) go(("Golang")) -.-> go/CommandLineandEnvironmentGroup(["Command Line and Environment"]) go(("Golang")) -.-> go/NetworkingGroup(["Networking"]) go/FunctionsandControlFlowGroup -.-> go/if_else("If Else") go/FunctionsandControlFlowGroup -.-> go/functions("Functions") go/CommandLineandEnvironmentGroup -.-> go/command_line("Command Line") go/NetworkingGroup -.-> go/processes("Processes") go/NetworkingGroup -.-> go/exit("Exit") subgraph Lab Skills go/if_else -.-> lab-149062{{"Beginner's Guide to Go Programming"}} go/functions -.-> lab-149062{{"Beginner's Guide to Go Programming"}} go/command_line -.-> lab-149062{{"Beginner's Guide to Go Programming"}} go/processes -.-> lab-149062{{"Beginner's Guide to Go Programming"}} go/exit -.-> lab-149062{{"Beginner's Guide to Go Programming"}} end

💡 First Go Program

Let's start by creating our first Go program. Right-click the sidebar to create a new file called helloWorld.go in your project folder.

Image Description

Note: We recommend using WebIDE (VS Code like) for a better experience. Learn more about the WebIDE Usage Guide here.

You also can create a new file using the touch command:

touch helloWorld.go

Now, open the file and write the following code:

package main

import "fmt"

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

The first line, package main, indicates that this program belongs to the main package. The second line, import "fmt", imports the Go fmt package, which allows us to format text input and output. The main function is where the program starts execution, and inside it, fmt.Println("hello, world") will print hello, world to the terminal.

To run the program, open the terminal and enter the following command:

go run helloWorld.go

If everything is set up correctly, you should see the output:

hello, world

This is a simple "Hello World" program. Now, let's explain the code and operations line by line.

Program Structure and Syntax

In Go, a package is the basic unit of code management. Every Go program begins with a package declaration. In this case, package main tells Go that the code is part of the main program that will be executed.

The import "fmt" statement imports the Go fmt package, which is used for input and output. Go has a rich standard library, which allows us to perform many tasks with ease. The fmt package is used to format text output, as we saw in the previous step.

Next, we define the main function:

func main() {
}

In Go, all functions must begin with func. Notice that the opening brace { is placed at the end of the line. This is a Go convention, and it’s different from other programming languages that might place the opening brace on a new line.

If you mistakenly place the opening brace on a new line like this:

func main()
{
}

You will get a compilation error:

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

This is because Go expects the opening brace to be directly on the same line.

The key statement in the program is fmt.Println("hello, world"), which calls the fmt package's Println function to print the string "hello, world" to the console. This function automatically adds a newline character at the end of the string.

Running the Program

Go is a compiled language, but when we use the go run command, Go first compiles the source code and then runs the resulting executable. So, the command:

go run helloWorld.go

is equivalent to running these two commands:

## Compile the program
go build helloWorld.go

## Execute the compiled program
./helloWorld

To try a new example, let's modify the program to greet other Gophers. Create a new file called helloGopher.go, and replace the code with:

You can create a new file using the touch command:

touch helloGopher.go
package main

import "fmt"

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

Now, instead of using go run, we'll use go build to compile the program, then run the generated executable:

## Compile the program
go build helloGopher.go

## Run the compiled executable
./helloGopher

This will output:

hello Gopher.
hello Gopher.
hello Gopher.

Common Functions in the fmt Package

In Step 1, we used the Println() function from the fmt package to print output. The fmt package is one of the most commonly used packages in Go and offers several functions for formatting output.

Here are three common output functions:

  1. fmt.Print() – Outputs the text without a newline.
  2. fmt.Println() – Outputs the text with a newline.
  3. fmt.Printf() – Outputs formatted text.

Let's explore these functions in more detail. Create a new file called 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", "London")
}

Run the program using the go run command:

go run fmt.go

Explanation:

  • fmt.Print("hello") and fmt.Print("world") output text on the same line because Print does not add a newline.
  • fmt.Println() outputs a newline to separate the lines.
  • fmt.Printf("%s\n", "London") formats the output using the %s placeholder for the string "London".

Here’s a quick comparison of the functions:

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

The fmt package also provides other functions for reading input, error handling, and more, which will be covered in later exercises.

Summary

In this lab, we've written our first Go program, learned about the structure of Go programs, and explored the basic functions of the fmt package for output. We also practiced running Go programs and learned the difference between Print, Println, and Printf. You should now have a basic understanding of Go syntax and program execution.