Are you ready to turbo-charge your software? Do you want a simple programming language that compiles fast? That runs fast? That makes it easy to distribute your work to users? Then you're ready for Go!
Go is a programming language that focuses on simplicity and speed. It's simpler than other languages, so it's quicker to learn. And it lets you harness the power of today's multi-core computer processors, so your programs run faster. This chapter will show you all the Go features that will make your life as a developer easier, and make your users happier.
Every program has parts that only apply in certain situations. "This code should run if there's an error. Otherwise, that code should run." Almost every program contains code that should be run only when a certain condition is true. So almost every programming language provides
if statements that let you determine whether to run segments of code. Go is no exception.
You may also need some parts of your code to run repeatedly. Like most languages, Go provides
for loops that run sections of code more than once. We'll learn to use both
for in this chapter!
It's your turn. You've been calling functions like a pro. But the only functions you could call were the ones Go defined for you. In this chapter, we're going to show you how to create your own functions. We'll learn how to declare functions with and without parameters. We'll declare functions that return a single value, and we'll learn how to return multiple values so that we can indicate when there's been an error. And we'll learn about pointers, which allow us to make more memory-efficient function calls.
It's time to get organized. So far, we've been throwing all our code together in a single file. As our programs grow bigger and more complex, that's going to quickly become a mess.
In this chapter, we'll show you how to create your own packages to help keep related code together in one place. But packages are good for more than just organization. Packages are an easy way to share code between your programs. And they're an easy way to share code with other developers.
A whole lot of programs deal with lists of things. Lists of addresses. Lists of phone numbers. Lists of products. Go has two ways of storing lists built-in. This chapter will introduce the first: arrays. You'll learn about how to create arrays, how to fill them with data, and how to get that data back out again. Then you'll learn about processing all the elements in array, first the hard way with
for loops, and then the easy way with
for ... range loops.
We've learned we can't add more elements to an array. That's a real problem for our program, because we don't know in advance how many pieces of data our file contains. But that's where Go slices come in. Slices are a collection type that can grow to hold additional items — just the thing to fix our program! We'll also see how slices can provide an easier way for users to provide data to all your programs, and how they can help you write functions that are more convenient to call.
Throwing things in piles is fine, until you need to find something again. You've already seen how to create lists of values using arrays and slices. You've seen how to apply the same operation to every value in an array or slice. But what if you need to work with a particular item? To find it, you'll have to start at the beginning of the array or slice, and look through Every. Single. Value.
What if there were a kind of collection where every value had a label on it? You could quickly find just the value you needed! In this chapter, we'll look at maps, which do just that.
Sometimes you need to store more than one type of data. We learned about slices, which store a list of values. Then we learned about maps, which map a list of keys to a list of values. But both of these data structures can only hold values of one type. Sometimes, you need to group together values of several types. Think of mailing addresses, where you have to mix street names (strings) with postal codes (integers). Or student records, where you have to mix student names (strings) with grade point averages (floating-point numbers). You can't mix value types in slices or maps. But you can if you use another type called a struct. We'll learn all about structs in this chapter!
There's more to learn about defined types. In the previous chapter, we showed you how to define a type with a struct underlying type. What we didn't show you was that you can use any type as an underlying type.
And do you remember methods — the special kind of function that's associated with values of a particular type? We've been calling methods on various values throughout the book, but we haven't shown you how to define your own methods. In this chapter, we're going to fix all of that. Let's get started!
Mistakes happen. Sometimes, your program will receive invalid data, from user input, a file you're reading in, or elsewhere. In this chapter, you'll learn about encapsulation: a way to protect your struct type's fields from that invalid data. That way you'll know your field data is safe to work with!
We'll also show you how to embed other types within your struct type. If your struct type needs methods that already exist on another type, you don't have to copy and paste the method code. You can embed the other type within your struct type, and then use the embedded type's methods just as if they were defined on your own type!
Sometimes you don't care about the particular type of a value. You don't care about what it is. You just need to know that it will be able to do certain things. That you'll be able to call certain methods on it. You don't care whether you have a
Pen or a
Pencil, you just need something with a
Draw method. You don't care whether you have a
Car or a
Boat, you just need something with a
That's what Go interfaces accomplish. They let you define variables and function parameters that will hold any type, as long as that type defines certain methods.
Every program encounters errors. You should plan for them. Sometimes handling an error can be as simple as reporting it and exiting the program. But other errors may require additional action. You may need to close opened files or network connections, or otherwise clean up, so your program doesn't leave a mess behind. In this chapter, we'll show you how to defer cleanup actions so they happen even when there's an error. We'll also show you how to make your program panic in those (rare) situations where it's appropriate, and how to recover afterwards.
Working on one thing at a time isn't always the fastest way to finish a task. Some big problems can be broken into smaller tasks. Goroutines let your program work on several different tasks at once. Your goroutines can coordinate their work using channels, which let them send data to each other and synchronize so that one goroutine doesn't get ahead of another. Goroutines let you take full advantage of computers with multiple processors, so that your programs run as fast as possible!
Are you sure your software is working right now? Really sure? Before you sent that new version to your users, you presumably tried out the new features to ensure they all worked. But did you try the old features to ensure you didn’t break any of them? All the old features? If that question makes you worry, your program needs automated testing. Automated tests ensure your program’s components work correctly, even after you change your code. Go's
testing package and
go test tool make it easy to write automated tests, using only the skills that you've already learned!
This is the 21st century. Users want web apps. Go’s got you covered there, too! The Go standard library includes packages to help you host your own web applications and make them accessible from any web browser. So we’re going to spend the final two chapters of the book showing you how to build web apps.
The first thing your web app needs is the ability to respond when a browser sends it a request. In this chapter, we'll learn to use the
net/http package to do just that.
Your web app needs to respond with HTML, not plain text. Plain text is fine for e-mails and social media posts. But your pages need to be formatted. They need headings and paragraphs. They need forms where your users can submit data to your app. To do any of that, you need HTML code.
And eventually, you'll need to insert data into that HTML code. Which is why Go offers the
html/template package, a powerful way to include data in your app's HTML responses. Templates are key to building bigger, better web apps, and in this final chapter, we'll show you how to use them!
Some programs need to write data to files, not just read data. Throughout the book, when we've wanted to work with files, you had to create them in your text editor for your programs to read. But some programs generate data, and when they do, they need to be able to write data to a file.
We used the
os.OpenFile function to open a file for writing earlier in the book. But we didn't have space then to fully explore how it worked. In this appendix, we'll show you everything you need to know in order to use
We've covered a lot of ground! We'll miss you, but before you go, we wouldn't feel right about sending you out into the world without a little more preparation. We've saved six important topics for this appendix.