The Deeper Love of Go (John Arundel) (Z-Library)

Author: John Arundel

商业

No Description

📄 File Format: PDF
💾 File Size: 1.7 MB
12
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
(This page has no text content)
📄 Page 2
The Deeper Love of Go John Arundel Bitfield Consulting February 20, 2025 © 2022 John Arundel
📄 Page 3
The Deeper Love of Go Praise for The Deeper Love of Go Introduction What’s this? What you’ll need Where to find the code examples What you’ll learn How to use this book The love of Go 1. Happy Fun Books Hello, world Our first program Packages Imports Functions Declaring a function Calling a function A challenge Creating a hello function Function ordering Dealing with data Values Variables Assigning values to variables Creating your own variables Adding a printBook function Declaring function parameters Here’s what we know so far 2. Data and types New data types Numeric data Parameter types The int type Variable declarations
📄 Page 4
Zero values and default values Type checking Type mismatch errors A plausible bug Structured data Introducing structs Declaring a new struct type Struct variables and values Combining declaration and assignment Struct literals Accessing struct fields Struct parameters Here’s what we know so far 3. Tests Self-testing code What does “it works” mean? How could we test this? Designing for testability The tools we need Conditional statements Comparison operators The panic function Writing the test Testing the test Functions that return results The return statement Running the test The fmt.Sprintf function Passing the test The testing package Declaring a test Creating a module The go test command Detecting a bug Interpreting the failure output A better failure message The naming of tests
📄 Page 5
Tests as docs, with gotestdox Updating main Making changes, guided by tests Updating the test Failing the test Updating the function Changing the format Passing the test Creating a package main is not importable The books package Updating the test Updating the main package Creating a cmd subfolder Checking the results Here’s what we know so far 4. Slicing & dicing Slices Slice variables Slice literals Indexing slices Finding the length of a slice Modifying slice elements Appending to slices A collection of books Setting up the world Comparing slices The updated test A dummy GetAllBooks Implementing GetAllBooks A global catalog variable Rewriting list Improving the output format A for ... range loop The blank identifier Unique identifiers Finding a specific book
📄 Page 6
Specifying a book uniquely Designing GetBook to take a book ID Parallel tests Adding the ID field to Book A dummy GetBook What does GetBook need to do? Implementing the algorithm A first attempt at GetBook Handling the “not found” case Returning multiple results Boolean values Returning a bool result from GetBook Testing the ok value The happy path The sad path Adding IDs to the catalog Fixing the tests Here’s what we know so far 5. Map mischief A find command Looking up a book by ID Implementing find Command-line arguments and os.Args Checking arguments A more efficient data structure Big-O notation Introducing the map Choosing the map type Map literals Turning maps into slices Using maps.Values Iterators Using slices.Collect Slices and maps have a lot in common Direct lookups in maps Zero values for structs The ok syntax
📄 Page 7
Putting it all together Road testing Iteration order of maps Flaky tests Sorting structs by field Modifying the catalog The magic function Testing AddBook Postconditions and preconditions A better AddBook test A hint of disquiet Race conditions in parallel tests Stepping on each other’s toes Data races De-globalising the catalog Making catalog a parameter A test data helper Fixing the tests Initializing the real catalog Here’s what we know so far 6. Objects behaving badly Objects and methods The mysterious t Methods on t Methods are syntactic sugar for functions Defining methods Turning BookToString into a method The receiver Calling String automatically Updating the tools Adding methods to the catalog Methods can only be added to local types Defining a new type Catalog is a distinct type The GetBook and AddBook methods Updating the tests to call methods The test catalog
📄 Page 8
Updating the tools Updating GetCatalog Pointers Objects as abstractions Validation Making Copies idiot-proof A non-validating SetCopies method An unexpected problem Assignment creates a copy Function parameters are also passed “by copy” The SetCopies bug Pointers are references The & and * operators Copies versus references: an analogy Pointers can be “write” as well as “read” Automatic dereferencing of struct pointers Pointer types Adding validation to SetCopies When validation fails Returning errors Testing for “no error” Testing for a validation error Creating error values Here’s what we know so far There’s more to come! About this book Who wrote this? Feedback Free updates to future editions Join my Code Club The Power of Go: Tools The Power of Go: Tests Know Go Further reading Credits
📄 Page 9
Praise for The Deeper Love of Go A great way to dive into Go! —Max VelDink One of the best technical books I have read in a very long time. —Paul Watts John is both a superb engineer and, just as importantly, an excellent teacher / communicator. —Luke Vidler A fantastic example of good technical writing. Clear, concise and easily digestible. —Michael Duffy This book’s writing style feels as if John is speaking to you in person and helping you along the way. —@rockey5520 Very well written, friendly, and informative. —Chris Doyle John’s writing is personable, human and funny—his examples are realistic and relevant. The test-driven instruction teaches Go in a deep, meaningful and engaging way. —Kevin Cunningham The book takes a very easy-to-follow, step-by-step approach to Go. The writing is very friendly and accessible. This would probably be my pick for the absolute beginner to computer programming who wants to learn Go. —Jonathan Hall A joy to read. Highly recommended for anyone starting with Go! —Ryunosuke Zoran
📄 Page 10
Introduction Hello, and welcome to learning Go! It’s great to have you here. What’s this? This book is an introduction to the Go programming language, suitable for complete beginners. If you don’t know anything about Go yet, or programming, but would like to learn, you’re in the right place. If you do already have some experience with Go, or with programming in other languages, don’t worry: this book is for you too! You’ll learn some ideas, techniques, and ways of tackling problems that even many advanced Go programmers don’t know. I hope to also help you fill in a few gaps in your knowledge that you may not even be aware of. What you’ll need You’ll need to install Go on your computer, if you don’t have it already. Follow the instructions on the Go website to download and install Go: https://go.dev/learn/
📄 Page 11
While all you need to write and run Go programs is a terminal and a text editor, you’ll find it very helpful to use an editor that has specific support for Go. For example, Visual Studio Code has excellent Go integration. While not essential, it’s a great idea to use some kind of version control software (for example, Git) to track and share your source code. I won’t go into the details of how to install and use Git in this book, but if you’re not already familiar with it, I recommend you learn at least the basics. Go to GitHub to find out more. Where to find the code examples There are dozens of challenges for you to solve throughout the book, each designed to help you test your understanding of the concepts you’ve just learned. If you run into trouble, or just want to check your code, each challenge is accompanied by a complete sample solution, with tests. All these solutions are also available in a public GitHub repo here: https://github.com/bitfield/love Each listing in the book is accompanied by a GitHub link with its name and number (for example, Listing hello/1, and clicking it will take you straight to the code for that program. What you’ll learn By reading through this book and completing the exercises, you’ll learn: How to manage data in Go using built-in types, user-defined struct types, and collections such as maps and slices How to write and test functions, including functions that return multiple results and error values How to use objects to model problems in Go, and how to add behaviour to objects using methods
📄 Page 12
How to use pointers to write methods that modify objects, and how to use types and validation to make your Go packages easy to use How to use this book Throughout this book we’ll be working together to develop a project in Go. Each chapter introduces a new feature or concept, and sets you some goals to achieve. Goals are marked with GOAL in bold. Each goal also comes with one or more hints, in case you’d like a little assistance, and once you’ve either solved the problem or given up in disgust, there’s a complete solution for you to look at. Don’t you hate books that have questions, but no answers? So do I. The love of Go Go is an unusually fun and enjoyable language to write programs in, and I hope to communicate something of my own love of Go to you in this book. It’s a relatively simple language, which isn’t the same as easy, of course. Programming is not easy, and no language makes it easy. Some just make it a little more fun than others. So let’s get started!
📄 Page 13
1. Happy Fun Books Do not taunt Happy Fun Ball. —“Saturday Night Live”, February 1991 Welcome aboard! It’s your first day as a Go developer at Happy Fun Books, a publisher and distributor of books for people who like cheerful reading in gloomy times. I’m so glad you could join us, because we have a very important job for you: you’ll be helping to build our new online bookstore using Go. Hello, world Don’t worry if that sounds a bit intimidating: we’ll start from scratch, and work our way up in easy stages. Actually, that’s what experienced programmers do, too, if they’re wise. In other words, we don’t start by trying to build something complicated like an e-commerce system. That’s much too difficult. Instead, we start with the simplest thing we can imagine, and get that working first. Then we add a tiny increment to it that gets us a little bit closer to what we need to end up with.
📄 Page 14
Our first program Let’s start with about the simplest program imaginable: one that just prints a message. If we can write, run, and understand that program, we’ll have covered a lot of useful ground already. Here’s the program: (Listing hello/1) Traditionally, the message we print when we write our first program in any language is “Hello, world”. Seems appropriate, doesn’t it? And you can see this text in the program code. Don’t worry about the other stuff for the moment: let’s just run the program first, then analyse how it works. Make a new folder on your computer—it doesn’t matter where—and use your text editor to create a file named main.go. Copy the example program to this file and save it. Now open your terminal application in this folder and run the following command: go run main.go If all goes well, you should see a friendly message: Hello, world package main import "fmt" func main() { fmt.Println("Hello, world") }
📄 Page 15
Packages Now let’s take a closer look at the program that produces this message. How does it work? It begins with this: All Go code, it turns out, belongs to some package. A package is just an arbitrary way of grouping related bits of code together, so that they can be used as a single unit. You can name your packages whatever you like, but there always has to be at least one package named main if you want to produce a runnable program. For any file containing source code, we need to tell Go what package it belongs to, which is why every Go file must begin with a package clause, as this one does. Imports Next comes this line: This is called a declaration: it declares something to Go about this program. So, what are we declaring here? As we’ve just seen, a Go program must have at least a main package, but if you want to use other packages, you’re welcome. All you need to do is add an import declaration like this, naming the extra package you want to use. In this case, it’s one called fmt. We’ll see what it’s for in a moment. Functions package main import "fmt"
📄 Page 16
Here’s another declaration. It’s telling Go about a new function that we’re defining: The func keyword, followed by a name (in this case main), declares a new function. So what’s a function? Declaring a function Just like a package, a function is a way of organising your code into a little unit and giving it a name. A single program can contain many packages, and each of those packages can contain many functions. And, just as the main package is special, because it’s the package that imports all others, the main function is special too. It’s where the execution of your program will actually start, so it’s the function that calls all others, if there are any others. Notice that this line ends with an opening curly brace, {. That means “Here comes the function body”. Go considers everything following the opening curly brace to be part of the body of the function we’re defining, until it sees a corresponding closing brace, which ends the function definition. Calling a function Our main function body is nice and simple: it just contains this single line: This is a statement. Whereas a declaration (such as the import declaration we just saw) just gives Go some descriptive information about our program (“We’re going to use the fmt package”), a statement tells Go to do something: “Print this message!”, for example. func main() { fmt.Println("Hello, world")
📄 Page 17
To call a function, we write its name, prefixed by the name of the package it belongs to (fmt.Println), and followed by a list of arguments in parentheses (“Hello, world”). fmt, which Go programmers like to pronounce as “fumpt”, deals with formatting text in various ways, including printing it to the terminal. And the specific function we’re using here is Println, which is short for “print line”. It prints whatever message we give it: Hello, world If we’d written a different message here, then that message would be printed instead when the program runs. Try changing the message, running the program again with go run main.go, and seeing what happens. So we’ve already learned quite a bit from even this fairly short program: how to declare a package, how to import other packages, how to define a function, how to call a function, and how to pass arguments to it. We also learned one way to print things, which is handy. A challenge Now here’s your first code challenge: to extend this program in an interesting way, using what you’ve just learned. Creating a hello function GOAL: Modify this program to add a declaration for a new function named hello. Your function should print the same “Hello, world” message that we’ve just seen. Modify the main function so that, instead of calling fmt.Println to print the message, it calls your new hello function. Check the result by running the go run main.go command again. If you’re not sure what to do, or you’d like a hint, read on.
📄 Page 18
HINT: Let’s start with how to declare our new hello function. You know that the func keyword introduces a new function, and you’ve seen how it’s used to declare main. You can use it in exactly the same way to declare your hello function. Can you see what to do? Inside the curly braces marking the body of the hello function, we need some code that prints the “Hello, world” message. Well, you already know how to do that: the exact same way that main does it. Finally, you need to modify the existing main function so that it calls hello instead of fmt.Println. And you know that you can call a function by writing its name, followed by parentheses (if there are no arguments, then you don’t need to put anything between the parentheses, but they still need to be there). If that function is in a different package, like fmt, then we need to use that package name as a prefix to the function call, but that’s not the case here. When the function we’re calling is in the “current” package—the one we’re in right now—then we can just give its name, without a prefix. SOLUTION: Well, here’s how I did it. See how it compares to your version: package main import "fmt" func hello() { fmt.Println("Hello, world") } func main() { hello() }
📄 Page 19
(Listing hello/2) Function ordering By the way, it doesn’t matter in what order you define your functions: you don’t have to define the function before you can call it. You can write your functions in whatever order you think is most logical for people reading the program. To me, that usually means putting the most important or commonly-used functions first, but it’s up to you. Dealing with data So, do we have a bookstore yet? Not quite, but we’re on the way. What’s the least we could do that would still be of some use to the staff of Happy Fun Books? Well, one thing we could do is, instead of printing “Hello, world”, we could print a list of books that are in stock. How would we do that? Simply printing a fixed message would be no good here, because Happy Fun Books has many branches, and the stock at each branch changes frequently. While the logic of our program (“print all the books”) won’t change, the specific data it deals with will vary from place to place and time to time. Values By “data”, we really just mean some piece of information, like the title of a book, its price, or the address of a customer. These are all data values—bits of data. So can we distinguish usefully between different kinds of data? Yes. For example, some data is in the form of text (a book title, for example). We call this string data, meaning a sequence of things, like “a string of pearls”, only in this case it’s a string of letters. We’ve used a string value already in our “Hello, world” program. It was the message we passed to fmt.Println:
📄 Page 20
Notice that when this message is printed, it doesn’t include the quote characters (") at either end. These aren’t part of the string itself: they’re just markers, indicating to Go where the string begins and ends. A piece of data like "Hello, world" is called a value. Suppose our bookstore is very small, and only has one book in stock at the moment. We could print its details by writing them as a string value: (Listing books/1) If you want to run this program, you can create a new folder for it, open a new main.go file, and copy this code into it. Or you can edit the “Hello, world” program we wrote earlier in this chapter, so that it looks like this one. Then use go run main.go as you did before. Notice what’s different about this program. We have two statements in the main function now, not just one. They’re both function calls, and they both call fmt.Println, but with different arguments—different values. And we said that, while the logic of the program won’t change, the data might. We probably won’t need to change the “Books in stock:” message, but we certainly will need to change the second message, about the specific book we have in stock. fmt.Println("Hello, world") package main import "fmt" func main() { fmt.Println("Books in stock:") fmt.Println("'Master and Commander', by Patrick O'Brian") }
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