Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Mastering Go
  • Table Of Contents Toc
  • Feedback & Rating feedback
Mastering Go

Mastering Go

By : Mihalis Tsoukalos
4.8 (27)
close
close
Mastering Go

Mastering Go

4.8 (27)
By: Mihalis Tsoukalos

Overview of this book

Mastering Go, now in its fourth edition, remains the go-to resource for real-world Go development. This comprehensive guide delves into advanced Go concepts, including RESTful servers, and Go memory management. This edition brings new chapters on Go Generics and fuzzy Testing, and an enriched exploration of efficiency and performance. As you work your way through the chapters, you will gain confidence and a deep understanding of advanced Go topics, including concurrency and the operation of the Garbage Collector, using Go with Docker, writing powerful command-line utilities, working with JavaScript Object Notation (JSON) data, and interacting with databases. You will be engaged in real-world exercises, build network servers, and develop robust command-line utilities. With in-depth chapters on RESTful services, the WebSocket protocol, and Go internals, you are going to master Go's nuances, optimization, and observability. You will also elevate your skills in efficiency, performance, and advanced testing. With the help of Mastering Go, you will become an expert Go programmer by building Go systems and implementing advanced Go techniques in your projects.
Table of Contents (19 chapters)
close
close
16
Other Books You May Enjoy
17
Index

Running Go code

You now need to know how to execute hw.go or any other Go application. As will be explained in the two subsections that follow, there are two ways to execute Go code: as a compiled language, using go build, or by mimicking a scripting language, using go run. So let us find out more about these two ways of running Go code.

Compiling Go code

To compile Go code and create a binary executable file, we need to use the go build command. What go build does is create an executable file for us to distribute and execute manually. This means that when using go build, an extra step is required to run the executable file.

The generated executable is automatically named after the source code filename without the .go file extension. Therefore, because of the hw.go source filename, the executable will be called hw. If this is not what you want, go build supports the -o option, which allows you to change the filename and the path of the generated executable file. As an example, if you want to name the executable file a helloWorld, you should execute go build -o helloWorld hw.go instead. If no source files are provided, go build looks for a main package in the current directory.

After that, you need to execute the generated executable binary file on your own. In our case, this means executing either hw or helloWorld. This is shown in the following output:

$ go build hw.go
$ ./hw
Hello World!

Now that we know how to compile Go code, let us continue using Go as if it were a scripting language.

Using Go like a scripting language

The go run command builds the named Go package, which in this case is the main package implemented in a single file, creates a temporary executable file, executes that file, and deletes it once it is done—to our eyes, this looks like using a scripting language while the Go compiler still creates a binary executable. In our case, we can do the following:

$ go run hw.go
Hello World!

Using go run is a better choice when testing code. However, if you want to create and distribute an executable binary, then go build is the way to go.

Important formatting and coding rules

You should know that Go comes with some strict formatting and coding rules that help a developer avoid rookie mistakes and bugs—once you learn these few rules and Go idiosyncrasies as well as the implications they have on your code, you will be free to concentrate on the actual functionality of your code. Additionally, the Go compiler is here to help you follow these rules with its expressive error messages and warnings. Last, Go offers standard tooling (gofmt) that can format your code for you, so you never have to think about it.

The following is a list of important Go rules that will help you while reading this chapter:

  • Go code is delivered in packages, and you are free to use the functionality found in existing packages. There is a Go rule that says that if you import a package, you should use it in some way (call a function or use a datatype), or the compiler is going to complain. There exist exceptions to this rule that mainly have to do with packages that initialize connections with database and TCP/IP servers, but they are not important for now. Packages are covered in Chapter 6, Go Packages and Functions.
  • You either use a variable or you do not declare it at all. This rule helps you avoid errors such as misspelling an existing variable or function name.
  • There is only one way to format curly braces in Go.
  • Coding blocks in Go are embedded in curly braces, even if they contain just a single statement or no statements at all.
  • Go functions can return multiple values.
  • You cannot automatically convert between different data types, even if they are of the same kind. As an example, you cannot implicitly convert an integer to a floating point.

Go has more rules, but the preceding ones are the most important and will keep you going for most of the book. You are going to see all these rules in action in this chapter as well as in other chapters. For now, let’s consider the only way to format curly braces in Go because this rule applies everywhere.

Look at the following Go program named curly.go:

package main
import (
    "fmt"
)
func main() 
{
    fmt.Println("Go has strict rules for curly braces!")
}

Quick tip: Enhance your coding experience with the AI Code Explainer and Quick Copy features. Open this book in the next-gen Packt Reader. Click the Copy button (1) to quickly copy code into your coding environment, or click the Explain button (2) to get the AI assistant to explain a block of code to you.

The next-gen Packt Reader is included for free with the purchase of this book. Unlock it by scanning the QR code below or visiting https://www.packtpub.com/unlock/9781805127147.

Although it looks just fine, if you try to execute it, you will be disappointed because the code will not compile and, therefore, you will get the following syntax error message:

$ go run curly.go
# command-line-arguments
./curly.go:7:6: missing function body
./curly.go:8:1: syntax error: unexpected semicolon or newline before {

The official explanation for this error message is that Go requires the use of semicolons as statement terminators in many contexts, and the compiler implicitly inserts the required semicolons when it thinks that they are necessary. Therefore, putting the opening curly brace ({) in its own line will make the Go compiler insert a semicolon at the end of the previous line (func main()), which is the main cause of the error message.

The correct way to write the previous code is the following:

package main
import (
    "fmt"
)
func main() {
    fmt.Println("Go has strict rules for curly braces!")
}

After learning about this global rule, let us continue by presenting some important characteristics of Go.

Create a Note

Modal Close icon
You need to login to use this feature.
notes
bookmark search playlist download font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Delete Note

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Edit Note

Modal Close icon
Write a note (max 255 characters)
Cancel
Update Note

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY