Introducing Go Build Reliable, Scalable Programs (Caleb Doxsey) (Z-Library)

Author: Caleb Doxsey

GO

Perfect for beginners familiar with programming basics, this hands-on guide provides an easy introduction to Go, the general-purpose programming language from Google. Author Caleb Doxsey covers the language’s core features with step-by-step instructions and exercises in each chapter to help you practice what you learn. Go is a general-purpose programming language with a clean syntax and advanced features, including concurrency. This book provides the one-on-one support you need to get started with the language, with short, easily digestible chapters that build on one another. By the time you finish this book, not only will you be able to write real Go programs, youll be ready to tackle advanced techniques.

📄 File Format: PDF
💾 File Size: 2.8 MB
40
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
Caleb Doxsey Introducing Go BUILD RELIABLE, SCALABLE PROGRAMS
📄 Page 2
(This page has no text content)
📄 Page 3
Caleb Doxsey Boston Introducing Go Build Reliable, Scalable Programs
📄 Page 4
978-1-491-94195-9 [LSI] Introducing Go by Caleb Doxsey Copyright © 2016 Caleb Doxsey. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/ institutional sales department: 800-998-9938 or corporate@oreilly.com. Editors: Brian MacDonald and Meghan Blanchette Production Editor: Shiny Kalapurakkel Copyeditor: Jasmine Kwityn Proofreader: James Fraleigh Indexer: WordCo Indexing Services, Inc. Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest January 2016: First Edition Revision History for the First Edition 2016-01-06: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781491941959 for release details. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
📄 Page 5
Table of Contents Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii 1. Getting Started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Machine Setup 1 Text Editors 2 The Terminal 2 Environment 2 Go 3 Your First Program 4 How to Read a Go Program 5 Exercises 8 2. Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Numbers 10 Integers 10 Floating-Point Numbers 10 Example 11 Strings 12 Booleans 13 Exercises 16 3. Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 How to Name a Variable 20 Scope 20 Constants 21 Defining Multiple Variables 22 An Example Program 22 Exercises 23 iii
📄 Page 6
4. Control Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 The for Statement 26 The if Statement 27 The switch Statement 29 Exercises 31 5. Arrays, Slices, and Maps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Arrays 33 Slices 36 append 37 copy 37 Maps 38 Exercises 42 6. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Your Second Function 43 Variadic Functions 47 Closure 47 Recursion 48 defer, panic, and recover 49 panic and recover 50 Pointers 51 The * and & operators 51 new 52 Exercises 53 7. Structs and Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Structs 56 Initialization 56 Fields 57 Methods 57 Embedded Types 58 Interfaces 59 Exercises 62 8. Packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 The Core Packages 63 Strings 64 Input/Output 67 Files and Folders 68 Errors 70 Containers and Sort 70 iv | Table of Contents
📄 Page 7
Hashes and Cryptography 73 Servers 75 TCP 75 HTTP 77 RPC 78 Parsing Command-Line Arguments 79 Creating Packages 79 Documentation 81 Exercises 82 9. Testing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Exercises 86 10. Concurrency. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Goroutines 87 Channels 89 Channel Direction 91 Select 91 Buffered Channels 92 An Example 93 Exercises 96 11. Next Steps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 Study the Masters 97 Make Something 98 Team Up 98 A. Answers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Table of Contents | v
📄 Page 8
(This page has no text content)
📄 Page 9
Introduction Although originally designed by Google for the kinds of problems Google works on —large, distributed network applications—Go is now a general-purpose program‐ ming language useful in a wide variety of software domains. Many companies have started using Go because of its simplicity, ease of use, performance, low barrier of entry, and powerful tooling. This book was written to help new programmers learn Go. Although there is an abundance of technical resources available for Go, most are geared toward experi‐ enced engineers. My goal here is to provide a more gentle introduction to the language. Who Should Read This Book This book is written for relatively inexperienced programmers who know nothing about Go. Although not exhaustive, it does cover all of the basics, and should leave you well positioned to tackle the more advanced material available on the language. The book also covers rudimentary programming skills via the exercises at the end of each chapter. Navigating This Book This book is organized as follows: • Chapters 1 through 4 introduce the Go toolset and the basics of the language • Chapters 5 through 7 describe more complex types and functions • Chapters 8 and 9 describe packages and testing • Chapter 10 introduces concurrency For best results, the book should be read in order, as each chapter builds on the con‐ cepts covered in the preceding chapters. Each chapter ends with a set of exercises, and vii
📄 Page 10
it’s important to actually complete them—it’s by solving problems like these that you learn to program. In particular, typing out the examples (and not just reading them) can help significantly. Online Resources You’ll want to check out the following resources: • The Official Go Website • The Go Tour Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. Using Code Examples This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a signifi‐ cant amount of example code from this book into your product’s documentation does require permission. viii | Introduction
📄 Page 11
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Introducing Go by Caleb Doxsey (O’Reilly). Copyright 2016 Caleb Doxsey, 978-1-4919-4195-9.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. Safari® Books Online Safari Books Online is an on-demand digital library that deliv‐ ers expert content in both book and video form from the world’s leading authors in technology and business. Technology professionals, software developers, web designers, and business and crea‐ tive professionals use Safari Books Online as their primary resource for research, problem solving, learning, and certification training. Safari Books Online offers a range of plans and pricing for enterprise, government, education, and individuals. Members have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kauf‐ mann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more information about Safari Books Online, please visit us online. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at bit.ly/introducing-go. To comment or ask technical questions about this book, send email to bookques‐ tions@oreilly.com. Introduction | ix
📄 Page 12
For more information about our books, courses, conferences, and news, see our web‐ site at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia x | Introduction
📄 Page 13
CHAPTER 1 Getting Started Go is a general-purpose programming language with advanced features and a clean syntax. Because of its wide availability on a variety of platforms, its robust well- documented common library, and its focus on good software engineering principles, Go is a great programming language to learn. This book assumes no prior knowledge of Go, and is intended to serve as an easy introduction to the language. All of the language’s core features will be covered in short, concise chapters that should prepare you to write real Go programs and tackle some of the more advanced resources available on the language (online documenta‐ tion, books, talks, etc.). Although this book is suitable for inexperienced programmers, if you have never pro‐ grammed before you will probably find the material too difficult to follow. You may benefit from consulting a more general programming resource before diving into the material here, but in all honesty, most students need the kind of hands-on, personal support that you might find in a classroom setting or one on one with an experienced developer. Machine Setup This book contains many code samples and exercises. For best results, you should try to run these examples on your own computer as you work your way through each chapter. But before you can write your first Go program, there are a few things you will need to set up. 1
📄 Page 14
Text Editors Go is a very readable, succinct language and so any text editor will work for editing files. There are plug-ins that add a few helpful features (like autocomplete and format-on-save) for many popular editors, but those plug-ins are not necessary to learn the language. If you’re not sure what to use, I recommend using GitHub’s Atom —it’s free, cross-platform, and easy to install from the Atom website. The Terminal Go is a compiled language, and like many languages, it makes heavy use of the com‐ mand line. If you’re coming from a language that does most things through an IDE (such as Java or C#), this may be a bit intimidating, but thankfully, the Go tools are fairly easy to use. As a reminder, here’s how you can get to a terminal: Windows On Windows, the terminal (also known as the command prompt) can be brought up by pressing the Windows key + R (hold down the Windows key, then press R), typing cmd.exe, and hitting Enter. OS X On OS X, the terminal can be reached by navigating to Finder → Applications → Utilities → Terminal. Environment Environment variables are a mechanism provided by your operating system for alter‐ ing the behavior of a program without having to change it. An environment is a col‐ lection of these variables, each of which has a name and a corresponding value. For example, there is a TEMP environment variable that stores the location of a directory on your computer where temporary files are stored. The Go toolset uses an environment variable called GOPATH to find Go source code. Although you’re welcome to set the GOPATH to anything you want, to make things eas‐ ier we will set it to be the same as your home directory: Windows On Windows, user information is typically stored in C:\Users\<USERNAME>, where <USERNAME> would be replaced with your username (e.g., C:\Users \alice). Windows comes with a predefined environment variable called USERPRO FILE, which you can use to set your GOPATH. Open a new terminal window and enter the following: setx GOPATH %USERPROFILE% 2 | Chapter 1: Getting Started
📄 Page 15
If you’re using a version of Windows prior to Vista, this command may not work, so you can also set environment variables by navigating to Control Panel → Sys‐ tem → Advanced → Environment Variables. OS X On OS X, user information is typically stored in /Users/<USERNAME>, where <USERNAME> would be replaced with your username (e.g., /Users/alice). On OS X, we will set GOPATH using a special initialization file for the terminal called .bash_profile. Open a terminal and enter the following: echo 'export GOPATH=$HOME\n' >> ~/.bash_profile Close the terminal, reopen it, and enter the following: env Among many other environment variables, you should see an entry for GOPATH. Go Go is both the name of the programming language and the name for the toolset used to build and interact with Go programs. Before you begin working with Go, you’ll need to install the Go toolset. Download and run the installer for your platform from golang.org/dl. To confirm everything is working, open a terminal and type the following: go version You should see the following (your version number and operating system may be slightly different): go version go1.5 windows/amd64 If you get an error about the command not being recognized, try restarting your computer. The Go toolset is made up of several different commands and subcommands. You can pull up a list of those commands by typing: go help With Go installed and working, you now have everything you need to write your first Go program. Machine Setup | 3
📄 Page 16
Your First Program Traditionally, the first program you write in any programming language is called a “Hello, World” program—a program that simply outputs Hello, World to your ter‐ minal. Let’s write one using Go. First, create a new folder where you can store our “Hello, World” program. Create a folder named ~/src/golang-book/chapter1. From the terminal, you can do this by entering the following commands: On Windows md src\golang-book\chapter1 On OS X mkdir -p src/golang-book/chapter1 Open your text editor, create a new file, and enter the following: package main import "fmt" // this is a comment func main() { fmt.Println("Hello, World") } Make sure your file is identical to what is shown here and save it as main.go in the folder we just created. Open up a new terminal and type in the following: cd src/golang-book/chapter1 go run main.go You should see Hello, World displayed in your terminal. The go run command takes the subsequent files (separated by spaces), compiles them into an executable saved in a temporary directory, and then runs the program. If you didn’t see Hello, World displayed, you may have made a mistake when typing in the program. The Go compiler will give you hints about where the mistake lies. Like most compilers, the Go compiler is extremely pedantic and has no tolerance for mistakes. 4 | Chapter 1: Getting Started
📄 Page 17
1 Files in the fmt package start with package fmt. How to Read a Go Program Let’s look at this program in more detail: package main import "fmt" // this is a comment func main() { fmt.Println("Hello, World") } Go programs are read top to bottom, left to right (like a book). The first line says this: package main This is known as a package declaration, and every Go program must start with it. Packages are Go’s way of organizing and reusing code. There are two types of Go pro‐ grams: executables and libraries. Executable applications are the kinds of programs that we can run directly from the terminal (on Windows, they end with .exe). Libra‐ ries are collections of code that we package together so that we can use them in other programs. We will explore libraries in more detail later; for now, just make sure to include this line in any program you write. The next line is blank. Computers represent newlines with a special character (or sev‐ eral characters). Newlines, spaces, and tabs are known as whitespace (because you can’t see them). Go mostly doesn’t care about whitespace—we use it to make pro‐ grams easier to read (you could remove this line and the program would behave in exactly the same way). On the following line, we see this: import "fmt" The import keyword is how we include code from other packages to use with our program. The fmt package (shorthand for format) implements formatting for input and output. Given what we just learned about packages, what do you think the fmt package’s files would contain at the top of them?1 Notice that fmt is surrounded by double quotes. The use of double quotes like this is known as a string literal, which is a type of expression. In Go, strings represent a sequence of characters (letters, numbers, symbols, etc.) of a definite length. Strings are described in more detail in the next chapter, but for now the important thing to How to Read a Go Program | 5
📄 Page 18
keep in mind is that an opening " character must eventually be followed by a closing " character and anything in between the two is included in the string (the " character itself is not part of the string). The line that starts with // is known as a comment. Comments are ignored by the Go compiler and are there for your own sake (or whoever picks up the source code for your program). Go supports two different styles of comments: // comments in which all the text between the // and the end of the line is part of the comment, and /* */ comments where everything between the asterisks is part of the comment (and may include multiple lines). After this, you see a function declaration: func main() { fmt.Println("Hello, World") } Functions are the building blocks of a Go program. They have inputs, outputs, and a series of steps called statements that are executed in order. All functions start with the keyword func followed by the name of the function (main, in this case), a list of zero or more parameters surrounded by parentheses, an optional return type, and a body which is surrounded by curly braces. This function has no parameters, doesn’t return anything, and has only one statement. The name main is special because it’s the func‐ tion that gets called when you execute the program. The final piece of our program is this line: fmt.Println("Hello, World") This statement is made of three components. First, we access another function inside of the fmt package called Println (that’s the fmt.Println piece); Println means “print line.” Then we create a new string that contains Hello, World and invoke (also known as call or execute) that function with the string as the first and only argument. At this point, you’ve already seen a lot of new terminology. Sometimes it’s helpful to deliberately read your program out loud. One reading of the program we just wrote might go like this: Create a new executable program that references the fmt library and contains one function called main. That function takes no arguments and doesn’t return anything. It accesses the Println function contained inside of the fmt package and invokes it using one argument—the string Hello, World. The Println function does the real work in this program. You can find out more about it by typing the following in your terminal: godoc fmt Println Among other things, you should see the output shown in Figure 1-1. 6 | Chapter 1: Getting Started
📄 Page 19
Figure 1-1. Output of godoc fmt Println Println formats using the default formats for its operands and writes to standard out‐ put. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered. Go is a very well-documented programming language, but this documentation can be difficult to understand unless you are already familiar with programming languages. Nevertheless, the godoc command is extremely useful and a good place to start when‐ ever you have a question. Back to the function at hand, this documentation is telling you that the Println func‐ tion will send whatever you give to it to standard output (i.e., the output of the termi‐ nal you are working in). This function is what causes Hello, World to be displayed. In the next chapter, we will explore how Go stores and represents things like Hello, World by learning about types. How to Read a Go Program | 7
📄 Page 20
Exercises 1. What is whitespace? 2. What is a comment? What are the two ways of writing a comment? 3. Our program began with package main. What would the files in the fmt package begin with? 4. We used the Println function defined in the fmt package. If you wanted to use the Exit function from the os package, what would you need to do? 5. Modify the program we wrote so that instead of printing Hello, World it prints Hello, my name is followed by your name. 8 | Chapter 1: Getting Started
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List