Go Programming Language For Dummies
By Wei-Meng Lee
()
About this ebook
Ready, set, program with Go!
Now is the perfect time to learn the Go Programming Language. It’s one of the most in-demand languages among tech recruiters and developers love its simplicity and power. Go Programming Language For Dummies is an easy way to add this top job skill to your toolkit. Written for novice and experienced coders alike, this book traverses basic syntax, writing functions, organizing data, building packages, and interfacing with APIs.
Go—or GoLang, as it’s also known—has proven to be a strong choice for developers creating applications for the cloud-based world we live in. This book will put you on the path to using the language that’s created some of today’s leading web applications, so you can steer your career where you want to Go!
- Learn how Go works and start writing programs and modules
- Install and implement the most powerful third-party Go packages
- Use Go in conjunction with web services and MySQL databases
- Keep your codebase organized and use Go to structure data
With this book, you can join the growing numbers of developers using Go to create 21st century solutions. Step inside to take start writing code that puts data in users’ hands.
Wei-Meng Lee
Wei-Meng Lee (Microsoft .NET MVP) is a technologist and co-founder of Active Developer, a technology company specializing in hands-on training on the latest technologies. He is an established developer and trainer specializing in .NET and wireless technologies.Wei-Meng speaks regularly at international conferences and has authored and co-authored numerous books on .NET, XML and wireless technologies, including .Net Mobile Web Developer's Guide, C#.Net Web Developer's Guide with CDROM, VB.NET Developer's Guide with CDROM, and Webmaster's Guide to the Wireless Internet (Syngress). He writes extensively for the O'Reilly Network on topics ranging from .NET to Mac OS X. He is also the author of Windows XP Unwired (O'Reilly & Associates) and is currently working on Programming the .NET Compact Framework, also from O'Reilly.
Read more from Wei Meng Lee
SwiftUI For Dummies Rating: 0 out of 5 stars0 ratingsPython Machine Learning Rating: 5 out of 5 stars5/5Beginning Swift Programming Rating: 0 out of 5 stars0 ratingsBeginning Android Application Development Rating: 0 out of 5 stars0 ratingsBeginning Android 4 Application Development Rating: 1 out of 5 stars1/5Beginning Ethereum Smart Contracts Programming: With Examples in Python, Solidity, and JavaScript Rating: 0 out of 5 stars0 ratings
Related to Go Programming Language For Dummies
Related ebooks
JavaScript Essentials For Dummies Rating: 0 out of 5 stars0 ratingsJavaScript Programming: Pushing the Limits Rating: 0 out of 5 stars0 ratingsTest-Driven Development in Go: A practical guide to writing idiomatic and efficient Go tests through real-world examples Rating: 0 out of 5 stars0 ratingsBeyond Silicon Rating: 5 out of 5 stars5/5Ultimate Microservices with Go Rating: 0 out of 5 stars0 ratingsAurelia in Action Rating: 0 out of 5 stars0 ratingsMastering Kotlin for Android 14: Build powerful Android apps from scratch using Jetpack libraries and Jetpack Compose Rating: 0 out of 5 stars0 ratingsGo Programming Cookbook Rating: 0 out of 5 stars0 ratingsGetting a Networking Job For Dummies Rating: 0 out of 5 stars0 ratingsSpeech Coding Algorithms: Foundation and Evolution of Standardized Coders Rating: 0 out of 5 stars0 ratingsReal-World Svelte: Supercharge your apps with Svelte 4 by mastering advanced web development concepts Rating: 0 out of 5 stars0 ratingsBeginning DotNetNuke Skinning and Design Rating: 0 out of 5 stars0 ratingsProgramming Backend with Go Rating: 0 out of 5 stars0 ratingsExt JS in Action Rating: 0 out of 5 stars0 ratingsData Engineering with Databricks Cookbook: Build effective data and AI solutions using Apache Spark, Databricks, and Delta Lake Rating: 0 out of 5 stars0 ratingsNW.js Essentials Rating: 0 out of 5 stars0 ratingsJavascript Assessment Test Rating: 0 out of 5 stars0 ratingsHTML5 Multimedia Development Cookbook Rating: 0 out of 5 stars0 ratingsHeroku Cloud Application Development Rating: 0 out of 5 stars0 ratingsMySQL 5.1 Plugin Development Rating: 0 out of 5 stars0 ratingsMastering Go Programming: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsJBoss Weld CDI for Java Platform Rating: 0 out of 5 stars0 ratingsStart Concurrent: An Introduction to Problem Solving in Java with a Focus on Concurrency, 2014 Rating: 0 out of 5 stars0 ratingsPro Spring Boot 2: An Authoritative Guide to Building Microservices, Web and Enterprise Applications, and Best Practices Rating: 0 out of 5 stars0 ratingsAutomated Testing A Complete Guide - 2019 Edition Rating: 0 out of 5 stars0 ratingsMastering Java: A Comprehensive Guide to Programming Excellence Category Rating: 0 out of 5 stars0 ratings
Programming For You
Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsLearn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5HTML in 30 Pages Rating: 5 out of 5 stars5/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Spies, Lies, and Algorithms: The History and Future of American Intelligence Rating: 4 out of 5 stars4/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5iPhone For Dummies Rating: 0 out of 5 stars0 ratingsC# Programming from Zero to Proficiency (Beginner): C# from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratingsGrokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Java for Beginners: A Crash Course to Learn Java Programming in 1 Week Rating: 5 out of 5 stars5/5Tiny Python Projects: Learn coding and testing with puzzles and games Rating: 4 out of 5 stars4/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsPython: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5
Reviews for Go Programming Language For Dummies
0 ratings0 reviews
Book preview
Go Programming Language For Dummies - Wei-Meng Lee
Introduction
Today, if you’re a programmer, you have lots of options when it comes to choosing a programming language. Popular programming languages include C++, C#, Go, Java, JavaScript, Python, R, Swift, and many more. Each language is designed to solve a different set of problems and, depending on what you’re going to create (mobile apps, web apps, desktop apps), you may end up learning one or more of these languages.
So, why Go? Turns out that three engineers at Google were frustrated with the various toolsets that they were working on and set out to design a new language that would address the criticisms of other languages while at the same time keeping their useful features.
Go was designed to
Use static typing and have the run-time efficiency of C
Have the readability and usability of languages like Python and JavaScript
Exhibit great performance in networking and multiprocessing
The problems with existing languages forced the team at Google to design a new language from the ground up, creating a lean and mean language designed for massive multithreading and concurrency.
This book covers the basics of Go (also known as Golang), one of the fastest-growing programming languages specifically designed to build faster and more scalable applications.
About This Book
In this code-intensive book, you’re encouraged to try out the various examples, which are designed to be compact, easy to follow, and easy to understand. But you don’t have to read the book from the first page to the last. Each chapter is designed to be independent, so you can dive in wherever you want and find the topics that you want to start learning.
If you’re short on time, you can safely skip sidebars (text in gray boxes) or anything marked with the Technical Stuff icon (more on that in "Icons Used in This Book," later in this Introduction). They’re interesting, but they aren’t essential to understanding the subject at hand.
Within this book, you may note that some web addresses break across two lines of text. If you’re reading this book in print and want to visit one of these web pages, simply key in the web address exactly as it’s noted in the text, pretending as though the line break doesn’t exist. If you’re reading this as an e-book, you’ve got it easy — just click the web address to be taken directly to the web page.
Foolish Assumptions
This book is for people who are new (or relatively new) to Go. I don’t assume that you’re familiar with Go programming, but I do assume the following:
You’re familiar with the basics of programming.
You’re familiar with the concept of data structures, such as dictionary, arrays, and structs.
You have a computer that you can use to try out the examples in this book.
Icons Used in This Book
Like other books in the For Dummies series, this book uses icons, little pictures in the margin to draw your attention to certain kinds of material. Here are the icons that I use:
Remember Whenever I tell you something useful or important enough that you’d do well to store the information somewhere safe in your memory for later recall, I flag it with the Remember icon.
Technical Stuff The Technical Stuff icon marks text that contains some for-nerds-only technical details or explanations that you’re free to skip.
Tip The Tip icon marks shortcuts or easier ways to do things, which I hope will make your life easier.
Warning The Warning icon marks text that contains a friendly but unusually insistent reminder to avoid doing something. You’ve been warned.
Beyond the Book
In addition to what you’re reading right now, this product comes with a free access-anywhere Cheat Sheet that tells you how to try Go online without installing any additional software, how to use the online tools to convert JSON to Go structs, and how to use Go in Docker. To get this Cheat Sheet, go to www.dummies.com and type Go Programming Language For Dummies Cheat Sheet in the Search box.
This book includes some downloadable content as well. Go to www.dummies.com/go/goprogramminglanguagefd to download all the code in the book.
Where to Go from Here
If you’re totally new to Go, you may want to start from the first chapter and follow through to the end. If you already have some basic knowledge of Go, you may want to head to Part 5, where you see Go in action. Regardless of how much experience you have, you can always turn to the index or table of contents to find the subjects that interest you most.
Finally, my advice to all beginners is: Practice, practice, practice. Type in the code in each chapter and make mistakes. The more mistakes you make, the better you’ll understand and remember the topics discussed.
Good luck and enjoy your newfound knowledge!
Part 1
Getting Started with Go
IN THIS PART …
Write your first Go program.
Discover the basic data types in Go and find out how to declare variables and constants.
Explore the various logical and comparison operators and use them to make decisions.
Understand how looping works and how you can execute code repeatedly.
Use functions to create Go programs that are easy to maintain and understand.
Chapter 1
Hello, Go!
IN THIS CHAPTER
Bullet Understanding why Go is the wave of the future
Bullet Installing Go on your computer
Bullet Working with an integrated development environment
Bullet Writing a Go program and understanding how it works
Bullet Seeing how Go compares to other languages
Go is an open-source programming language — one of the fastest-growing programming languages around — released by Google in 2009. It’s a multipurpose programming language specifically designed to build fast, scalable applications.
Technical Stuff Go comes from a pretty impressive team of people: Ken Thompson (designer and creator of Unix and C), Rob Pike (cocreator of UTF-8 and Unix format), and Robert Griesemer (a Google engineer). If you’re technically inclined, you may want to check out an article called Go at Google: Language Design in the Service of Software Engineering
(https://talks.golang.org/2012/splash.article), which discusses how Go was initially conceived to solve problems at Google.
In this chapter, I explain why learning Go is important for your career, where Go can be used, and how to get started with Go programming.
Tip Go is often referred to as Golang because of its web address: https://golang.org. However, the official name of the language is Go, so that’s how I refer to it throughout this book.
Seeing What Learning Go Can Do for You
You can learn many programming languages today, but Go stands out from the others for a few reasons:
Go is easy to learn. Go’s syntax makes it a readable language. It has no support for object-oriented programming (OOP), which means you don’t have to worry about classes and inheritance and the complexities that come with that.
Technical Stuff Object-oriented programming (OOP) is a programming paradigm that is based on the concept of objects (data). Instead of focusing on the functions and logics, OOP organizes software around data, or objects. A key concept in OOP is classes (sort of like templates). Suppose you want to display buttons in your application. Instead of writing the code to display each button individually, you can create a class to represent a generic button and use it to create buttons to display in your application. Each button has its own properties (characteristics). Using the concept of inheritance in OOP, you can create multiple subclasses of the button class to create different types of buttons, such as a rounded button, a rectangular button, and so on.
Go has fewer features than other programming languages. You don’t have to worry about the best way to solve a problem — there is only one right way to solve a problem in Go. This makes your codebase easy to maintain.
Go excels in concurrent programming. Go’s support for Goroutines makes it extremely easy to run multiple functions concurrently.
Tip Go has no support for generics (the ability to specify the actual data type until it’s actually used), but this may change as the language evolves.
If you still aren’t convinced that you should learn Go, perhaps this next bit of news will motivate you: In the Stack Overflow Developer Survey 2019 (https://insights.stackoverflow.com/survey/2019), Go developers were the third highest paid in the industry, behind Clojure and F# developers.
Although Go has been around for quite a while (since 2009), only recently did it get wide adoption by developers, thanks to the proliferation of cloud computing and microservices. Today, Go has been widely used by major companies such as Dailymotion, Dropbox, Google, and Uber.
Here are some examples of where Go can be used:
Cloud services: You can build scalable apps using Go on the Google Cloud Platform (GCP).
Networking apps: With Go’s support for Goroutines, you can use Go to build distributed servers and application programming interfaces (APIs).
Web services: You can use Go to build scalable and efficient web services.
Command-line apps: Because Go runs on multiple platforms, you can compile the same codebase and target different platforms (such as those running on macOS and Windows).
Installing Go on Your Machine
You’re probably very eager to get started with Go programming on your machine, so let’s get to it!
The easiest way to install Go is to go to https://golang.org/doc/install. This website automatically detects the operating system (OS) you’re using and shows you the button to click to download the Go installer (see Figure 1-1).
Snapshot of downloading the Go installer.FIGURE 1-1: Downloading the Go installer.
Tip This book code has been written and tested using Go version 1.15. When you’re reading this book, a new version of Go may have been released. In order to ensure that you can follow the examples in this book, I strongly suggest that you install the same version of Go that I’ve used. You can find it here:
macOS:https://golang.org/dl/go1.15.8.darwin-amd64.pkg
Windows:https://golang.org/dl/go1.15.8.windows-amd64.msi
Technical Stuff If you want to be able to choose the Go installer for each of the supported operating systems (Linux, macOS, and Windows), and even see the source code for Go, go to https://golang.org/dl/.
After you’ve downloaded the Go installer, double-click the installer to start the straightforward installation process. I recommend that you just use the default installation settings — you don’t need to change any of those settings.
In the following sections, I show you how to verify that your installation is performed successfully on macOS and Windows.
macOS
On macOS, the Go installer installs the Go distribution in the /usr/local/go directory. It also adds the /usr/local/go/bin directory to your PATH environment variable. You can verify this by entering the following command in the Terminal app (which you can find in the Applications/Utilities folder):
$ echo $PATH
You should see something like the following output (note the added path, highlighted in bold):
/Users/weimenglee/opt/anaconda3/bin:/Volumes/SSD/opt/anaco
nda3/condabin:/Users/weimenglee/flutter/bin:/Users/weimeng
lee/go/bin:/Users/weimenglee/.nvm/versions/node/v9.2.0/bin
:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/g
o/bin:/usr/local/share/dotnet:~/.dotnet/tools:/Library/App
le/usr/bin:/Library/Frameworks/Mono.framework/Versions/Cur
rent/Commands
Tip Make sure to restart the Terminal app after you've installed Go in order for the changes to take effect.
To verify that the installation is correct, type the following command in Terminal:
$ go version
You should see the version of Go installed on your system:
go version go1.15.8 darwin/amd64
Windows
On Windows, the Go installer installs the Go distribution in the C:\Go directory. It also adds the C:\Go\bin directory to your PATH environment variable. You can verify this by entering the following command in Command Prompt (which you can find by typing cmd in the Windows search box):
C:\Users\Wei-Meng Lee>path
You should see something like the following output (note the added path, highlighted in bold):
PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\
Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WIND
OWS\System32\OpenSSH\;C:\Program Files\dotnet\;C:\Program
Files\Microsoft SQL Server\130\Tools\Binn\;C:\Go\bin;
C:\Program Files\Git\cmd;C:\Program Files\Graphviz
2.44.1\bin;C:\Program Files\CMake\bin;C:\Program
Files\Docker\Docker\resources\bin;C:\ProgramData\DockerDes
ktop\version-bin;C:\Program Files\MySQL\MySQL Shell
8.0\bin\;C:\Users\Wei-Meng Lee\AppData\Local\
Microsoft\WindowsApps;;C:\Users\Wei-Meng Lee\
AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\Wei-
Meng Lee\.dotnet\tools;C:\Users\Wei-Meng Lee\go\bin
Tip Make sure to restart the Command Prompt window after you've installed Go in order for the changes to take effect.
To verify that the installation is correct, type the following command in Command Prompt:
C:\Users\Wei-Meng Lee>go version
You should now see the version of Go installed on your computer:
go version go1.15.8 windows/amd64
Using an Integrated Development Environment with Go
To develop applications using Go, you just need a text editor (such as Visual Studio Code, TextEdit on macOS, or even the old trusty NotePad), and you’re good to go (pun unintended). However, many developers prefer to use integrated development environments (IDEs) that can help them organize their code, as well as provide debugging support. Here is a partial list of IDEs that work with Go:
Visual Studio Code (https://code.visualstudio.com): Visual Studio Code from Microsoft is the mother of all code editors (and my personal favorite). Visual Studio Code is a full-featured code editor that supports almost all programming languages under the sun. Perhaps one of the most useful features of Visual Studio Code is IntelliSense, which helps to complete your statement as you type. It also comes with debugger support and an interactive console, as well as Git integration. Best of all, Visual Studio Code is free and has a very active community of Go developers, allowing you to extend its functionalities through the various plug-ins.
GoLand (www.jetbrains.com/go/): GoLand is a cross-platform IDE by JetBrains. It comes with coding assistance, a debugger, an integrated Terminal, and more. GoLand is a commercial IDE, and it has a 30-day trial.
The Go Playground (https://play.golang.org): The Go Playground (which isn’t really an IDE, but is worth a mention here) is a web service that runs on Go’s servers. It receives a Go program, compiles, links, runs it inside a sandbox, and then returns the output. The Go Playground is very useful when you need to test out some Go code quickly using a web browser.
Tip In this book, I use Visual Studio Code for Go development. To download Visual Studio Code, go to https://code.visualstudio.com/download. After you’ve downloaded and installed Visual Studio Code, launch it, and you should see the screen shown in Figure 1-2.
Tip In order for Visual Studio Code to recognize your Go language syntax, you also need to install an extension for it. Follow these steps to install the Go extension:
In Visual Studio Code, click the Extensions icon on the Activity Bar (see Figure1-3).
Snapshot of Launching Visual Studio Code for the first time.FIGURE 1-2: Launching Visual Studio Code for the first time.
Snapshot of the Extensions icon is located at the bottom of the Activity Bar.FIGURE 1-3: The Extensions icon is located at the bottom of the Activity Bar.
In the Search box for the Extensions panel, type Go.
You see a list of the Go extensions available (see Figure 1-4).
Select the first extension and click the Install button on the right.
That’s it! You’re ready to write your first program!
Snapshot of Searching for Go extensions for Visual Studio Code.FIGURE 1-4: Searching for Go extensions for Visual Studio Code.
Writing Your First Go Program
To write your first Go program, create a new file in Visual Studio Code by choosing File ⇒ New File. Then enter the following statements (see Figure 1-5):
package main
import fmt
func main() {
fmt.Println(Hello, world!
)
}
Snapshot of Writing the first Go program.FIGURE 1-5: Writing your first Go program.
When you’re done typing, press ⌘ +S (Ctrl+S) to save the file. Name the file main.go. If this is the first time you're writing a Go program using Visual Studio Code, it may prompt you to download additional plugins for Go. I recommend that you install the plugins.
Tip For this book, save your files to a folder named with the chapter number you’re reading. For example, save main.go in a folder named Chapter 1 in your home directory. On a Mac, that looks like this:
~/Chapter 1
|__main.go
In Windows, it looks like this:
C:\users\yourname\Chapter 1
|__main.go
After the file is saved, notice that your Go statements will now be color-coded — light blue for keywords such as package, import, and func; orange for strings like Hello, world! and fmt; and yellow for functions like main() and Println().
Compiling and running the program
After you've saved a program, you need to compile it so that you can run it.
You can run the program directly in Visual Studio Code. To do that, launch the Terminal by choosing Terminal ⇒ New Terminal. The Terminal now opens in Visual Studio Code (see Figure 1-6).
Next, change the directory to Chapter 1. In macOS, use the following command:
$ cd ~/Chapter 1
In Windows, use the following command:
$ cd C:\users\username\Chapter 1
To compile the main.go file, type the following command:
$ go build main.go
Snapshot of directly accessing the Terminal in Visual Studio Code.FIGURE 1-6: You can directly access the Terminal in Visual Studio Code.
The preceding command compiles the main.go program into an executable file. On macOS, after running the program, you see a file named main. To run it, use the following command:
$ ./main
Hello, world!
If you see the Hello, world! string printed, congratulations! You're now officially a Go programmer!
If you’re using Windows, the build command generates an executable named main.exe. To run it, use the following command:
C:\users\username\Chapter 1>main
Hello, world!
Because you often want to run the program immediately after compiling it, you can use the run option to compile and run the program straight away:
$ go run main.go
Understanding how a Go program works
Now that your Go program works, it's time to understand how. I’ll walk you through it line by line. The first line defines the package name for this program:
package main
Go programs are organized into packages. A package is a collection of source files grouped in a single directory. In this example, main is the name of the package stored in the Chapter 1 directory. If you have additional source files (.go files), they'll all belong to this main package (more on this in later chapters).
Tip You aren’t constrained to using main as the package name. You can use any package name you want. But this main package name has a special meaning: Packages with the name main will contain a function named main(), which serves as an entry point for your program to get started. Also, your package name and the name of the file containing