Statistics
6
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-01-11

AuthorThornton, Edward, Thornton, Edward

No description

Tags
No tags
ISBN: 8644637992
Publish Year: 2021
Language: 英文
File Format: PDF
File Size: 881.5 KB
Support Statistics
¥.00 · 0times
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.

(This page has no text content)
GO FOR BEGINNERS A Genius Guide to Go Programming EDWARD THORNTON
© Copyright 2021 - All rights reserved. It is not legal to reproduce, duplicate, or transmit any part of this document in either electronic means or in printed format. Recording of this publication is strictly prohibited and any storage of this document is not allowed unless with written permission from the publisher except for the use of brief quotations in a book review.
Contents Introduction 1. Why Go? Designed for Modern Conditions Advantages of Go Disadvantages of Go Who Should Use Go? Chapter Summary 2. Foundations of Golang Identifiers, Filenames, and Keywords Functions Data Types Constants Variables Operators Strings Times and Dates Chapter Summary 3. You’ve Got It Under Control (Structures) If-Else Switch-Case For For Range Break and Continue Labels: Goto Chapter Summary 4. Go Functions, What’s Your Function? Basics of Functions Return Values and Parameters Defer, Panic, and Tracing Built-in Functions Recursion Higher-Order Functions Closures Chapter Summary 5. Slices and Arrays
Arrays Slices Declaration Initialization Modifying Slices For and For Range with Slices Multidimensional Reslicing, Copying, and Appending Strings, Arrays, and Slices Sorting and Inverting Chapter Summary 6. Map Your Way to Success Declaration and Initialization Key Value Item For Range Slices and Maps Modifying your Maps Sorting Chapter Summary 7. Structs Introduction to Structs Anonymous Structs Metadata and Tags Chapter Summary 8. Packages—Not Just For Delivery Standard Library Overview Regexp Sync Accurate Computations Custom Packages Documenting your Package Package Distribution with Git External Packages, Libraries, and Projects Chapter Summary 9. Methods to the Golang Madness Differences between Functions and Methods Receivers and Methods as Pointers and Values Accepting Both Pointer and Value Types Embedded Types Inheritance and Multiple Inheritance Chapter Summary 10. Interfaces and Reflection Embedded Interface
Type Assertions Type Switches Implementing an Interface Sorter Interface Reading and Writing Empty Reflect Package Printf, Value, and Dynamic Interface Structs, Collections, and Higher-Order Functions Best Practices for Interfaces Chapter Summary 11. Reading and Writing With the Simple Power of Go Read: User Input Read and Write: Files Read: Files with a Buffer Read: Arguments from Command Line Read with Slices JSON Data Format XML Data Format Chapter Summary 12. Goroutines and Channels for Speedy Code About Concurrency and Parallelism Goroutines Synchronizing and Switching between Goroutines Channels Semaphore Pattern Channel Factory and Directionality Channels, Tickers, and Timeouts Chapter Summary 13. Testing and Handling Errors Run-Time Exceptions and Panic Panics and Recover Error Handling with Closures Testing and Benchmarking Assessing Code Performance Chapter Summary 14. Common Pitfalls and Patterns Pattern: Comma, OK Pattern: Visibility and Operator Pattern: Defer Common Pitfalls Chapter Summary Final Words
About the Author Other Titles by Edward Thornton References
Introduction What’s the programming language that professional software developers most want to learn? Would it surprise you to find out that it’s not Python or JavaScript? Nearly a third of developers chose Go as their top language to learn (Combs, 2020) after Google engineers created it to address problems with existing languages, such as slow speeds. It’s also associated with top pay rates in the industry. If you’re looking to learn a powerful language that manages to be relatively lightweight and still has the features that developers are looking for, you’ve come to the right place. Although the tech sector is currently getting the most use out of it, other companies, including American Express, Target, and IBM, have begun using the programming language as well. You may have picked up this book because you’ve already heard a lot about Go and want to add it to your programming arsenal. Or maybe you don’t have a lot of programming experience, so a lightweight language seems like it could be right up your alley. Perhaps your company is looking into adding Go to speed up the performance of its apps, or you’d like to get a job at a company like SoundCloud, Uber, BBC, or Dropbox. If you’re familiar with other languages, you can probably pick up Go in a few hours. With less programming experience, you’ll need to spend a bit longer to learn it. However, it’s very clear and doesn’t have the excess baggage that software development languages tend to add on over time since it’s a relatively youthful one.
In this book, before we dive into the basics of the language itself, you’ll discover why it’s so popular and why more and more programmers are adopting it. Go is more readable than many other languages, which makes using it for open-source programming a natural fit. You’ll learn about the foundations, including elementary types and strings, as well as control structures such as if-else and for range. You’ll find out about functions in Go and slices and arrays too. Maps and packages are important components of Go programming, and we’ve provided details about both in the book. In addition, you’ll learn about methods (and how they differ from functions), interfaces, and reflection. There’s information about reading the language, not to mention goroutines and channels. Finally, and maybe most importantly, we’ve included a chapter on testing and handling errors as well as a chapter on common pitfalls and patterns. Find out what mistakes many developers make, so you can avoid them yourself! Once you’ve learned the foundations of the language in this book, you’ll be ready to start programming in Golang. As a Go programmer myself, I’ve written this book to help others learn the language. I know what the pitfalls are, and I’ve helped other software developers like you get up to speed on Go pretty quickly. I think as many developers as possible should start learning it so they can build code that executes faster, is cleaner, and helps spread the popularity of open-source applications. The sooner you start reading the book, the sooner you’ll be able to start programming—it really is that simple! Go was designed to be learned fast, and to execute fast. So dive in and get started on your Golang; why wait any longer to add this powerful tool to your kit?
ONE Why Go? IN 2009, a team of Google employees introduced Go to the world. (It’s sometimes referred to as Golang to differentiate it from the well-known game of Go.) Supposedly, they started creating it while waiting for a program in another language to compile. The employees were frustrated by the limitations of the languages available at that time and decided to rethink programming from the very beginning, working from the ground up. Over time, computer languages (just like spoken ones) tend to accumulate extra baggage that gets in the way and slows down the speed of the code. Starting from scratch meant that they could build something lean, yet powerful enough to handle massive code. They also designed it to be open- source, so it’s easy to create new applications and use them in a variety of industries for many different purposes. First, a quick refresher on programs: they’re simply a set of instructions. Both compilers and interpreters take human code and translate it into machine-readable code. Compiled languages, like Go, are developed so that the target machine can read the code directly. Interpreter languages such as Python and Ruby don’t have the translation inside the source code and require a separate program to read and execute the code. Designed for Modern Conditions
Go was intentionally created to run on multiple cores, which allows programmers to scale when adding more cores. It also helps them create concurrency since goroutines execute in the background while other jobs are running. If you’re building a web app that requires data input from the user, for example, the goroutine can supply pre-populated text as the user is inputting. The program continues to run no matter how long it takes the concurrent processes to operate. The language uses goroutines instead of threads, which requires much less use of the machine’s RAM. That makes an app running on Go less likely to crash from running out of memory. Goroutines are functions that execute simultaneously with concurrent goroutines and work on any hardware. By contrast, threads execute the code under the logic of the program and are dependent on the specific hardware being used. Goroutines communicate with one another easily and without taking up a lot of power through channels. Threads don’t have an easy way to talk to one another, which results in communication between threads taking more time and power. As a result, goroutines are faster and cheaper than threads. Unlike some previous languages, Go is designed for cloud-based servers that most web developers use these days. It’s compilable on almost any machine and works on a variety of platforms as well. If you’ve been using Perl to watch a log, Python to deliver tweets, or Java to manage thousands of concurrent users, you’ll find that Go can accomplish all of these little tasks and more. Like Java, Go is compiled and needs no interpreter. That frees up a lot of power for the code itself, making it run much faster. Having lower system requirements also means that users will be able to use your app on older devices, which expands the potential market for your app and may land more money in your pocket. Advantages of Go Flexibility
This language can solve a lot of problems for developers. It can be used for network and system programming as well as audio/visual apps, such as YouTube. More modern developments, such as big data and machine learning, are possible with this language. Automatic documentation GoDoc will automatically generate the technical documentation for the code. It provides cross-references, examples of the code, and links to the repository for version control. This is especially key for open-source developers and makes it much easier to build apps based on another’s code. Embedded testing The language comes with an API for use in testing and profiling, as well as your own examples. In addition to basic testing, you can also run skip tests and parallel tests, among others. Static code analysis Using the metatool GoMetaLinter, you can debug your source code before running it by analyzing it against the code rules. Using automated static code analysis is not only faster than debugging manually, but it also avoids the usual human error in manual analysis. Detecting race condition When multiple threads compete, they may end up being completed in an unexpected order which results in errors that are hard to track down (this is known as race condition). The Go engineers decided to create an automatic detector to eliminate the problem, which also ensures backward compatibility. Disadvantages of Go
Lack of GUI library The lack of a GUI library is fine for single-page apps, but businesses that need both speed and GUI for their users typically choose Ruby instead. Otherwise, it’s a time-consuming job to try to connect libraries instead of using a native solution as you would with Python or Java. No generics Because of the way Go is designed, you may need to write more code to handle certain functions than you would for other languages. In languages that use generics, you can write algorithms with terms-to-be-specified-later that will then run when needed with the specific types as parameters. It helps reduce code repetition; you can write one function instead of two. Without this capability, you need to write more lines of code for each function instead. Error handling Although handling errors is pretty simple in Go, it may require a lot more code than other languages. Dependency management You can install different libraries with Go, but if the maintainer of the library uploads a version that's not backward-compatible, then anyone running your app will get an error. If the library isn’t installed, the program won’t compile. While there is a tool to help you manage this (Dep), it either forces you to load all the dependencies on the repository or store the package list. If you store on the repository, your code becomes much bigger because you’re also storing lines of dependency code. However, if you only store the package list, you may run into backward incompatibility issues which will cause your program to crash.
Who Should Use Go? This language is great for the underlying code on apps that require speed. It’s also good for high-performance apps that require scalability. Google uses it for its cloud services infrastructure; companies like YouTube, Netflix, and Soundcloud use Go for high loads on their platforms; Uber used it to improve map processing speeds so it takes less time to match a rider with a driver; data science organizations are using it more and more to process big data and make sense of it. Go is a great solution for fintech developers because it allows for a smooth connection between users and their financial institutions. Paypal has used it for scaling, AmEx for payments, and Salesforce for their “Einstein Analytics”. It’s also become the language of choice for programming on the blockchain, especially the Ethereum network. As you can see, Go is a good tool to have for almost any modern programmer. Whether it’s for system programming, network programming, web applications, or DevOps, the language is easy to use and read. And most importantly for the users of today, it’s much faster than many of the other available options.
Chapter Summary Go was designed by Google engineers who wanted a faster computer language that could take advantage of multiple cores. Because it is a younger language, it works well for modern applications that are located on the cloud instead of specific hardware and can run operations concurrently. Go is flexible and uses goroutines that run simultaneously without slowing down the speed, among other advantages. Golang’s GUI library is nonexistent, so it’s not preferred for apps that rely on GUI in addition to speed, among other disadvantages. Go is applicable in many different types of applications and industries, especially for those with high user loads or other big data needs. In the next chapter, you'll learn about the foundations of Go.
TWO Foundations of Golang IN THIS CHAPTER, we’ll delve into the foundations of Golang, which you can think of as the basic vocabulary for the language. Some of these you’ll be familiar with if you’ve done programming with similar languages such as C and C++. Identifiers, Filenames, and Keywords If you’re relatively new to programming, identifiers are the names of the program’s components as defined by the users. Identifiers in Go may be names of functions, constants, variables, statement labels, types, or package names. Go identifiers must be written in a specific way to be recognized by the program. It must start with a letter or underscore, not a number. The identifier itself can contain letters, numbers, and underscores. It’s case- sensitive, so while Go_lang and go_lang are different, they’re both valid names. Golang1 is OK, but 1Golang is not. You can’t use keywords such as “if” or “default”. Programmers find it best to keep the identifiers between 4 and 15 characters, though there’s technically no limit to the length. The underscore is a blank identifier and is used as an anonymous placeholder with a special meaning in certain parts of the program.
Go also has some identifiers that have been predeclared and can be used for constants, functions, and types. Constants: true, false, iota, nil Functions: make, copy, append, close, delete, plus others Types: int, uint, string, bool, error, plus others Filenames , which are used to identify each file uniquely, are typically written in lowercase and multiple words are separated with an underscore. Keywords , sometimes known as reserve words, already have a meaning in the language and therefore, as noted above, can’t be used for identifiers. There are 25 keywords in Go, including map, struct, goto, switch, import, and return. Functions In general, functions are blocks of code that perform a specific task. They’re also known as methods, subroutines, or procedures. Many functions follow the format of taking in data, processing it, and then returning the result. Functions can be “called” from within other functions. Once the function is called, the program leaves the code at that line, executes the function instructions line by line, then returns to the program, replacing the function with the result that it returned. Instead of continually rewriting code or copying and pasting for common tasks, functions can be reused over and over. Languages normally have several built-in functions that would otherwise require multiple lines of code, and programmers can also write their own to satisfy the need of their program. The variables inside the function are only live while the function is being executed, so you can use i to mean one thing in function_1 and something else in function_2, and the program will continue to run. In Go, every program has at least one function: main(). This is a function declaration, which tells the program the name of the function, the return type, parameters, and the definition. The definition is the set of instructions or the function body.
There are other standard functions in Go such as len(), which will give you the length of the argument, string, or array, depending on what was called. This is the syntax of a function in Go, or how it’s written in code: func function_name ( [parameter list] ) [return_types] } body of the function { where func starts the declaration, telling the program that a function is coming up function_name names the function being used parameter is similar to a placeholder, and gives the type, order, and number of parameters; there may be no parameters for a function return_types is the list of data types for the values the function returns; this isn’t always required body defines what the function does For example, suppose you wanted a function to show the maximum of two numbers, num1 and num2: func max (num 1, num2 int) int { result int //The program ignores anything after //, so you can type notes here. Note that this is a local variable declaration. if (num1 > num2) { result = num1 } else { result = num2 } return result
} Data Types The type of a variable specifies how much space it occupies and how the bit pattern should be interpreted. In Go, you can classify into four categories: 1. Boolean There are only two of these: true and false. Bool is one of the four elementary types. 2. Numeric These can be either integers or floating-point values. Examples of numeric types include uint8 (unsigned 8-bit integers from 0 to 255), int16 (signed 16-bit integers), and the like for integers. Floating points can be float32 (IEEE 32-bit floating-point), float64 (IEEE 64-bit floating-point, complex62 (float32 with real and imaginary parts), or complex128 (float64 with real and imaginary.) Both int and float are also elementary types. 3. Strings These represent the value of the string, which is a sequence of bytes. Once created, the string cannot be changed. Strings can be alphanumeric, such as in the iconic “helloworld”. A string is also an elementary type. 4. Derived types These include pointer types, array types, structure types, map types, etc., and will be discussed further in later chapters. Constants Like other statistically typed programs, the compiler either already knows or can figure out the type of every variable when it comes time to compile.
Unlike other languages, however, Go doesn’t allow you to mix numeric types. C, C++, or Java will convert smaller types (like “int”) into a larger one (like “float”) when the types are mixed. The Golang engineers thought that allowing these automatic conversions not only potentially makes them hard to read, but creates inconsistencies across different platforms. Since Go is designed to work on a variety of architectures, the language was designed to ask for explicit types instead. Unless you explicitly give a constant a type, it’s considered untyped, even if you give it a name. An untyped constant that’s an integer can only be used where integers are allowed. For example, you can’t assign an integer constant to a string or boolean variable. An untyped floating-point constant can be used wherever a floating point is permitted. All untyped constants in Go have default types. Constants that are integers default to “int”, floats default to “float64”, characters to “rune”, etc. When you declare a type, the constant becomes typed. Again, constants must be declared as their correct type, or else the program will return an error. Declare constants without a type unless you absolutely need them; declaring a type makes you lose the flexibility of being able to mix types in an operation. There are a few rules for constant expressions in Go. Comparison between two untyped constants results in an untyped boolean constant (“true”/”false”). Operands of the same type result in the same type. In other words, if they’re two untyped integer constants, the yield is an untyped integer constant. The expression “11/2” results in “5” rather than “5.5” because it’s truncated to an integer. If they’re not the same type, the result is the broader of the two according to this logic: integer<rune<floating-point<complex Variables