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.
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.
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.
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.
- 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
/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):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):Using an Integrated Development Environment with Go
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.
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:
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:
This package contains various functions to allow you to format and print to the console. It also contains functions to get a user's inputs.
The next block of code is the main entry point of your program:
Because the package name is main
, this main()
function will now serve as the starting point for your program to execute.
Finally, the following line calls the Println()
function from the fmt
package to print the string Hello, world!
to the console:
Making sense of the Go file structure
You should now have a good idea of how the Go program works. Let's dive a little deeper into how Go files are grouped together. As I mention in the previous section, all files in the same directory belong to the same package. So, let’s now add another file to the Chapter 1
directory
and name it show_time.go
. The Chapter 1
directory should now have one more file:
Notice that the file is part of the main
package (the first line reflects that). Also, you can import multiple packages by enclosing them within a pair of parentheses. In this case, we imported the time
package in addition to the fmt
package. Finally, we also added a function named displayTime()
, which displays the current date and time using the Now()
function from the time
package.
Because the displayTime()
function belongs to the main
package, it can also be called from main.go
:
Because there are now two files in the package (main
), you don't build the program using a specific filename. Instead, you just need to use the build
command within the Chapter 1
directory:
This time around, you'll see that there is a new file named Chapter_1
(in Windows, you’ll see a file named Chapter_1.exe
) created in the Chapter 1
directory.
To run it in macOS, type the following in Terminal:
Compiling for multiple operating systems
When you install Go, the Go installer automatically sets up a number of Go environment variables in order for your Go program to work correctly. Specifically, it auto-detects values of the host architecture and OS and sets the GOHOSTARCH
and GOHOSTOS
environment variables, respectively. The value of these two variables will be used as the target platform for your program to compile to.
To examine the values of these Go environment variables, use the env
command:
Operating Systems |
GOOS |
GOARCH |
---|---|---|
macOS |
|
|
Linux |
|
|
Windows |
|
|
To compile for the Windows OS, use the following command and options:
The preceding command compiles the package in the Chapter 1
folder to run on Windows and save the executable as Chapter_1-windows.exe
.
To compile for Linux, use the following command and options:
If you're running macOS or Linux, you can use the file
command to examine the various executables created for each platform:
Comparing Go with Other Languages
When learning a new programming language, it’s always helpful to try to compare it with another language that you may already be familiar with. Doing so allows you to try to map your current knowledge to the new language that you’re trying to learn.
In this section, I compare Go with two of the most commonly used programming languages used in the industry, Java and Python. Occasionally, I compare Go with C, because Go is syntactically similar to C. Go is often touted as the language with the speed of C and the productivity of Python.
If you aren’t familiar with any of the languages listed in this section, don’t worry! In this book, I cover all the features mentioned here.
BuildID=bSETwZgNDR5vlulRHnzw/KNpENRt9Hipd8Nu7HGDg/v38ZPzDs35yMw33hUxoz/Y_cNfU8fID2cCtz36hCq, not stripped
Comparing Go with Other Languages
When learning a new programming language, it’s always helpful to try to compare it with another language that you may already be familiar with. Doing so allows you to try to map your current knowledge to the new language that you’re trying to learn.
In this section, I compare Go with two of the most commonly used programming languages used in the industry, Java and Python. Occasionally, I compare Go with C, because Go is syntactically similar to C. Go is often touted as the language with the speed of C and the productivity of Python.
Syntax
In terms of syntax, Go is closer to C and Java, which use curly braces to enclose blocks of code. This syntax differs from Python, which uses indentation as a form of denoting blocks of code.
Like Python, Go functions are first-class citizens, whereas in Java everything revolves around classes, and you need a class just to enclose a function.
Unlike Python and Java, Go doesn’t have OOP support, and it doesn’t support inheritance. But it does have interfaces and structs that work just like classes.
Go is statically typed, like Java. It differs from Python, which is dynamically typed
Compilation
Whereas Python and Java are compiled to byte code, which is then interpreted and run on a virtual machine, Go compiles directly to machine code, which makes Go take the lead in terms of performance.
Like Python and Java, Go is also garbage collected. In programming, garbage collection (GC) is a form of automatic memory management. The garbage collector tries to reclaim memory occupied by objects that are no longer in use by the program.
Python is extremely memory intensive. Java is not much better because everything is heap allocated. But Go affords more control of memory usage.
Concurrency
Go has parallelism and concurrency built in, which means writing multi-threaded applications is very easy. Both Java and Python support concurrency through threading, but they aren’t as efficient as Go. In fact, concurrency is one of Go’s main selling points.
Library support
All three languages have huge library support — both standard and third-party libraries. A language’s survival depends in large part on its support for third-party libraries. That’s why Python has been so hot for the past couple of years — its support for third-party libraries for doing data analytics brings machine learning and deep learning readily to the masses. Although Go doesn’t have the scale of third-party library support that Python does because it’s young, the number of libraries for Go is growing.
No comments:
Post a Comment