在好例子网,分享、交流、成长!
您当前所在位置:首页Go 开发实例Go语言基础 → Head First Go

Head First Go

Go语言基础

下载此实例
  • 开发语言:Go
  • 实例大小:56.15M
  • 下载次数:7
  • 浏览次数:34
  • 发布时间:2022-10-19
  • 实例类别:Go语言基础
  • 发 布 人:temp22
  • 文件格式:.pdf
  • 所需积分:2
 相关标签: go

实例介绍

【实例简介】Head First Go

【实例截图】

【核心代码】

Table of Contents (the real thing)
how to use this book: Intro
Your brain on Go.
Here you are trying to learn something, while here your brain is, doing
you a favor by making sure the learning doesn’t stick. Your brain’s
thinking, “Better leave room for more important things, like which wild
animals to avoid and whether naked snowboarding is a bad idea.” So
how do you trick your brain into thinking that your life depends on
knowing how to program in Go?
“Who is this book for?”
“We know what you’re thinking”
“We know what your brain is thinking”
“Metacognition: thinking about thinking”
“Here’s what WE did”
“Read me”
“Acknowledgments”
Chapter 1
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 multicore 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.
“Ready, set, Go!”
“The Go Playground”
“What does it all mean?”
“What if something goes wrong?”
“Calling functions”
“The Println function”
“Using functions from other packages”
“Function return values”
“A Go program template”
“Strings”
“Runes”
“Booleans”
“Numbers”
“Math operations and comparisons”
“Types”
“Declaring variables”
“Zero values”
“Short variable declarations”
“Naming rules”
“Conversions”
“Installing Go on your computer”
“Compiling Go code”
“Go tools”
“Try out code quickly with “go run””
“Your Go Toolbox”
Chapter 2
Every program has parts that apply only in certain situations.
“This code should run if there’s an error. Otherwise, that other 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 conditional 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 loops that run sections of code more than
once. We’ll learn to use both conditionals and loops in this chapter!
“Calling methods”
“Making the grade”
“Multiple return values from a function or method”
“Option 1: Ignore the error return value with the blank
identifier”
“Option 2: Handle the error”
“Conditionals”
“Logging a fatal error, conditionally”
“Avoid shadowing names”
“Converting strings to numbers”
“Blocks”
“Blocks and variable scope”
“We’ve finished the grading program!”
“Only one variable in a short variable declaration has to be
new”
“Let’s build a game”
“Package names vs. import paths”
“Generating a random number”
“Getting an integer from the keyboard”
“Comparing the guess to the target”
“Loops”
“Init and post statements are optional”
“Using a loop in our guessing game”
“Breaking out of our guessing loop”
“Revealing the target”
“Congratulations, your game is complete!”
“Your Go Toolbox”
Chapter 3
You’ve been missing out.
You’ve been calling functions like a pro. But the only functions you
could call were the ones Go defined for you. Now, it’s your turn. 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.
“Some repetitive code”
“Formatting output with Printf and Sprintf”
“Formatting verbs”
“Formatting value widths”
“Formatting fractional number widths”
“Using Printf in our paint calculator”
“Declaring functions”
“Declaring function parameters”
“Using functions in our paint calculator”
“Functions and variable scope”
“Function return values”
“Using a return value in our paint calculator”
“The paintNeeded function needs error handling”
“Error values”
“Declaring multiple return values”
“Using multiple return values with our paintNeeded function”
“Always handle errors!”
“Function parameters receive copies of the arguments”
“Pointers”
“Pointer types”
“Getting or changing the value at a pointer”
“Using pointers with functions”
“Fixing our “double” function using pointers”
“Your Go Toolbox”
Chapter 4
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.
“Different programs, same function”
“Sharing code between programs using packages”
“The Go workspace directory holds package code”
“Creating a new package”
“Importing our package into a program”
“Packages use the same file layout”
“Package naming conventions”
“Package qualifiers”
“Moving our shared code to a package”
“Constants”
“Nested package directories and import paths”
“Installing program executables with “go install””
“Changing workspaces with the GOPATH environment
variable”
“Setting GOPATH”
“Publishing packages”
“Downloading and installing packages with “go get””
“Reading package documentation with “go doc””
“Documenting your packages with doc comments”
“Viewing documentation in a web browser”
“Serving HTML documentation to yourself with “godoc””
“The “godoc” server includes YOUR packages!”
“Your Go Toolbox”
Chapter 5
A whole lot of programs deal with lists of things.
Lists of addresses. Lists of phone numbers. Lists of products. Go has
two built-in ways of storing lists. 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.
“Arrays hold collections of values”
“Zero values in arrays”
“Array literals”
“Functions in the “fmt” package know how to handle arrays”
“Accessing array elements within a loop”
“Checking array length with the “len” function”
“Looping over arrays safely with “for...range””
“Using the blank identifier with “for...range” loops”
“Getting the sum of the numbers in an array”
“Getting the average of the numbers in an array”
“Reading a text file”
“Reading a text file into an array”
“Updating our “average” program to read a text file”
“Our program can only process three values!”
“Your Go Toolbox”
Chapter 6
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 current program! We’ll also
see how slices give users an easier way to provide data to all your
programs, and how they can help you write functions that are more
convenient to call.
“Slices”
“Slice literals”
“The slice operator”
“Underlying arrays”
“Change the underlying array, change the slice”
“Add onto a slice with the “append” function”
“Slices and zero values”
“Reading additional file lines using slices and “append””
“Trying our improved program”
“Returning a nil slice in the event of an error”
“Command-line arguments”
“Getting command-line arguments from the os.Args slice”
“The slice operator can be used on other slices”
“Updating our program to use command-line arguments”
“Variadic functions”
“Using variadic functions”
“Using a variadic function to calculate averages”
“Passing slices to variadic functions”
“Slices have saved the day!”
“Your Go Toolbox”
Chapter 7
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 value? 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.
“Counting votes”
“Reading names from a file”
“Counting names the hard way, with slices”
“Maps”
“Map literals”
“Zero values within maps”
“The zero value for a map variable is nil”
“How to tell zero values apart from assigned values”
“Removing key/value pairs with the “delete” function”
“Updating our vote counting program to use maps”
“Using for...range loops with maps”
“The for...range loop handles maps in random order!”
“Updating our vote counting program with a for...range loop”
“The vote counting program is complete!”
“Your Go Toolbox”
Chapter 8
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!
“Slices and maps hold values of ONE type”
“Structs are built out of values of MANY types”
“Access struct fields using the dot operator”
“Storing subscriber data in a struct”
“Defined types and structs”
“Using a defined type for magazine subscribers”
“Using defined types with functions”
“Modifying a struct using a function”
“Accessing struct fields through a pointer”
“Pass large structs using pointers”
“Moving our struct type to a different package”
“A defined type’s name must be capitalized to be exported”
“Struct field names must be capitalized to be exported”
“Struct literals”
“Creating an Employee struct type”
“Creating an Address struct type”
“Adding a struct as a field on another type”
“Setting up a struct within another struct”
“Anonymous struct fields”
“Embedding structs”
“Our defined types are complete!”
“Your Go Toolbox”
Chapter 9
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!
“Type errors in real life”
“Defined types with underlying basic types”
“Defined types and operators”
“Converting between types using functions”
“Fixing our function name conflict using methods”
“Defining methods”
“The receiver parameter is (pretty much) just another
parameter”
“A method is (pretty much) just like a function”
“Pointer receiver parameters”
“Converting Liters and Milliliters to Gallons using methods”
“Converting Gallons to Liters and Milliliters using methods”
“Your Go Toolbox”
Chapter 10
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!
“Creating a Date struct type”
“People are setting the Date struct field to invalid values!”
“Setter methods”
“Setter methods need pointer receivers”
“Adding the remaining setter methods”
“Adding validation to the setter methods”
“The fields can still be set to invalid values!”
“Moving the Date type to another package”
“Making Date fields unexported”
“Accessing unexported fields through exported methods”
“Getter methods”
“Encapsulation”
“Embedding the Date type in an Event type”
“Unexported fields don’t get promoted”
“Exported methods get promoted just like fields”
“Encapsulating the Event Title field”
“Promoted methods live alongside the outer type’s methods”
“Our calendar package is complete!”
“Your Go Toolbox”
Chapter 11
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 Steer method.
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.
“Two different types that have the same methods”
“A method parameter that can only accept one type”
“Interfaces”
“Defining a type that satisfies an interface”
“Concrete types, interface types”
“Assign any type that satisfies the interface”
“You can only call methods defined as part of the interface”
“Fixing our playList function using an interface”
“Type assertions”
“Type assertion failures”
“Avoiding panics when type assertions fail”
“Testing TapePlayers and TapeRecorders using type assertions”
“The “error” interface”
“The Stringer interface”
“The empty interface”
“Your Go Toolbox”
Chapter 12
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
afterward.
“Reading numbers from a file, revisited”
“Any errors will prevent the file from being closed!”
“Deferring function calls”
“Recovering from errors using deferred function calls”
“Ensuring files get closed using deferred function calls”
“Listing the files in a directory”
“Listing the files in subdirectories (will be trickier)”
“Recursive function calls”
“Recursively listing directory contents”
“Error handling in a recursive function”
“Starting a panic”
“Stack traces”
“Deferred calls completed before crash”
“Using “panic” with scanDirectory”
“When to panic”
“The “recover” function”
“The panic value is returned from recover”
“Recovering from panics in scanDirectory”
“Reinstating a panic”
“Your Go Toolbox”
Chapter 13
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!
“Retrieving web pages”
“Multitasking”
“Concurrency using goroutines”
“Using goroutines”
“Using goroutines with our responseSize function”
“We don’t directly control when goroutines run”
“Go statements can’t be used with return values”
“Sending and receiving values with channels”
“Synchronizing goroutines with channels”
“Observing goroutine synchronization”
“Fixing our web page size program with channels”
“Updating our channel to carry a struct”
“Your Go Toolbox”
Chapter 14
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 the skills that you’ve
already learned!
“Automated tests find your bugs before someone else does”
“A function we should have had automated tests for”
“We’ve introduced a bug!”
“Writing tests”
“Running tests with the “go test” command”
“Testing our actual return values”
“More detailed test failure messages with the “Errorf” method”
“Test “helper” functions”
“Getting the tests to pass”
“Test-driven development”
“Another bug to fix”
“Running specific sets of tests”
“Table-driven tests”
“Fixing panicking code using a test”
“Your Go Toolbox”
Chapter 15
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.
“Writing web apps in Go”
“Browsers, requests, servers, and responses”
“A simple web app”
“Your computer is talking to itself”
“Our simple web app, explained”
“Resource paths”
“Responding differently for different resource paths”
“First-class functions”
“Passing functions to other functions”
“Functions as types”
“What’s next”
“Your Go Toolbox”
Chapter 16
Your web app needs to respond with HTML, not plain text.
Plain text is fine for emails 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. That’s
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!
“A guestbook app”
“Functions to handle a request and check errors”
“Setting up a project directory and trying the app”
“Making a signature list in HTML”
“Making our app respond with HTML”
“The “text/template” package”
“Using the io.Writer interface with a template’s Execute
method”
“ResponseWriters and os.Stdout both satisfy io.Writer”
“Inserting data into templates using actions”
“Making parts of a template optional with “if” actions”
“Repeating parts of a template with “range” actions”
“Inserting struct fields into a template with actions”
“Reading a slice of signatures in from a file”
“A struct to hold the signatures and signature count”
“Updating our template to include our signatures”
“Letting users add data with HTML forms”
“Form submission requests”
“Path and HTTP method for form submissions”
“Getting values of form fields from the request”
“Saving the form data”
“HTTP redirects”
“Our complete app code”
“Your Go Toolbox”
Appendix A
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 os.OpenFile effectively!
“Understanding os.OpenFile”
“Passing flag constants to os.OpenFile”
“Binary notation”
“Bitwise operators”
“The bitwise AND operator”
“The bitwise OR operator”
“Using bitwise OR on the “os” package constants”
“Using bitwise OR to fix our os.OpenFile options”
“Unix-style file permissions”
“Representing permissions with the os.FileMode type”
“Octal notation”
“Converting octal values to FileMode values”
“Calls to os.OpenFile, explained”
Appendix B
We’ve covered a lot of ground, and you’re almost finished with this
book.
We’ll miss you, but before we let 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.
“#1 Initialization statements for “if””
“#2 The switch statement”
“#3 More basic types”
“#4 More about runes”
“#5 Buffered channels”
“#6 Further reading”

标签: go

实例下载地址

Head First Go

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
;
报警