6 | There is a suite of programs to build and process Go source code.
7 | Instead of being run directly, programs in the suite are usually invoked
8 | by the go program.
9 |
10 |
11 |
12 | The most common way to run these programs is as a subcommand of the go program,
13 | for instance as go fmt. Run like this, the command operates on
14 | complete packages of Go source code, with the go program invoking the
15 | underlying binary with arguments appropriate to package-level processing.
16 |
17 |
18 |
19 | The programs can also be run as stand-alone binaries, with unmodified arguments,
20 | using the go tool subcommand, such as go tool cgo.
21 | For most commands this is mainly useful for debugging.
22 | Some of the commands, such as pprof, are accessible only through
23 | the go tool subcommand.
24 |
25 |
26 |
27 | Finally the fmt and godoc commands are installed
28 | as regular binaries called gofmt and godoc because
29 | they are so often referenced.
30 |
31 |
32 |
33 | Click on the links for more documentation, invocation methods, and usage details.
34 |
9 | This document lists commonly used editor plugins and IDEs from the Go ecosystem
10 | that make Go development more productive and seamless.
11 | A comprehensive list of editor support and IDEs for Go development is available at
12 | the wiki.
13 |
14 |
15 |
Options
16 |
17 | The Go ecosystem provides a variety of editor plugins and IDEs to enhance your day-to-day
18 | editing, navigation, testing, and debugging experience.
19 |
20 |
21 |
22 |
Visual Studio Code:
23 | Go extension provides support for the Go programming language
24 |
GoLand: GoLand is distributed either as a standalone IDE
25 | or as a plugin for IntelliJ IDEA Ultimate
26 |
vim: vim-go plugin provides Go programming language support
27 |
28 |
29 | Note that these are only a few top solutions; a more comprehensive
30 | community-maintained list of
31 | IDEs and text editor plugins
32 | is available at the Wiki.
33 |
34 |
--------------------------------------------------------------------------------
/_content/doc/go-get-install-deprecation.md:
--------------------------------------------------------------------------------
1 |
5 |
6 | ## Overview
7 |
8 | Starting in Go 1.17, installing executables with `go get` is deprecated.
9 | `go install` may be used instead.
10 |
11 | In a future Go release, `go get` will no longer build packages; it will only
12 | be used to add, update, or remove dependencies in `go.mod`. Specifically,
13 | `go get` will act as if the `-d` flag were enabled.
14 |
15 | ## What to use instead
16 |
17 | To install an executable in the context of the current module, use `go install`,
18 | without a version suffix, as below. This applies version requirements and
19 | other directives from the `go.mod` file in the current directory or a parent
20 | directory.
21 |
22 | ```
23 | go install example.com/cmd
24 | ```
25 |
26 | To install an executable while ignoring the current module, use `go install`
27 | *with* a [version suffix](/ref/mod#version-queries) like `@v1.2.3` or `@latest`,
28 | as below. When used with a version suffix, `go install` does not read or update
29 | the `go.mod` file in the current directory or a parent directory.
30 |
31 | ```
32 | # Install a specific version.
33 | go install example.com/cmd@v1.2.3
34 |
35 | # Install the highest available version.
36 | go install example.com/cmd@latest
37 | ```
38 |
39 | In order to avoid ambiguity, when `go install` is used with a version suffix,
40 | all arguments must refer to `main` packages in the same module at the same
41 | version. If that module has a `go.mod` file, it must not contain directives like
42 | `replace` or `exclude` that would cause it to be interpreted differently if it
43 | were the main module.
44 |
45 | See [`go install`](#/ref/mod#go-install) for details.
46 |
47 | ## Why this is happening
48 |
49 | Since modules were introduced, the `go get` command has been used both to update
50 | dependencies in `go.mod` and to install commands. This combination is frequently
51 | confusing and inconvenient: in most cases, developers want to update a
52 | dependency or install a command but not both at the same time.
53 |
54 | Since Go 1.16, `go install` can install a command at a version specified on the
55 | command line while ignoring the `go.mod` file in the current directory (if one
56 | exists). `go install` should now be used to install commands in most cases.
57 |
58 | `go get`'s ability to build and install commands is now deprecated, since that
59 | functionality is redundant with `go install`. Removing this functionality
60 | will make `go get` faster, since it won't compile or link packages by default.
61 | `go get` also won't report an error when updating a package that can't be built
62 | for the current platform.
63 |
64 | See proposal [#40276](https://golang.org/issue/40276) for the full discussion.
65 |
--------------------------------------------------------------------------------
/_content/doc/go-logo-black.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/go-logo-black.png
--------------------------------------------------------------------------------
/_content/doc/go-logo-blue.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/go-logo-blue.png
--------------------------------------------------------------------------------
/_content/doc/go-logo-white.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/go-logo-white.png
--------------------------------------------------------------------------------
/_content/doc/gopher/README:
--------------------------------------------------------------------------------
1 | The Go gopher was designed by Renee French. (http://reneefrench.blogspot.com/)
2 | The design is licensed under the Creative Commons 3.0 Attributions license.
3 | Read this article for more details: https://blog.golang.org/gopher
4 |
--------------------------------------------------------------------------------
/_content/doc/gopher/appenginegopher.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/appenginegopher.jpg
--------------------------------------------------------------------------------
/_content/doc/gopher/appenginegophercolor.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/appenginegophercolor.jpg
--------------------------------------------------------------------------------
/_content/doc/gopher/appenginelogo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/appenginelogo.gif
--------------------------------------------------------------------------------
/_content/doc/gopher/biplane.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/biplane.jpg
--------------------------------------------------------------------------------
/_content/doc/gopher/bumper.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/bumper.png
--------------------------------------------------------------------------------
/_content/doc/gopher/bumper192x108.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/bumper192x108.png
--------------------------------------------------------------------------------
/_content/doc/gopher/bumper320x180.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/bumper320x180.png
--------------------------------------------------------------------------------
/_content/doc/gopher/bumper480x270.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/bumper480x270.png
--------------------------------------------------------------------------------
/_content/doc/gopher/bumper640x360.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/bumper640x360.png
--------------------------------------------------------------------------------
/_content/doc/gopher/doc.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/doc.png
--------------------------------------------------------------------------------
/_content/doc/gopher/fiveyears.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/fiveyears.jpg
--------------------------------------------------------------------------------
/_content/doc/gopher/frontpage.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/frontpage.png
--------------------------------------------------------------------------------
/_content/doc/gopher/gopherbw.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/gopherbw.png
--------------------------------------------------------------------------------
/_content/doc/gopher/gophercolor.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/gophercolor.png
--------------------------------------------------------------------------------
/_content/doc/gopher/gophercolor16x16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/gophercolor16x16.png
--------------------------------------------------------------------------------
/_content/doc/gopher/help.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/help.png
--------------------------------------------------------------------------------
/_content/doc/gopher/modelsheet.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/modelsheet.jpg
--------------------------------------------------------------------------------
/_content/doc/gopher/pencil/gopherhat.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/pencil/gopherhat.jpg
--------------------------------------------------------------------------------
/_content/doc/gopher/pencil/gopherhelmet.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/pencil/gopherhelmet.jpg
--------------------------------------------------------------------------------
/_content/doc/gopher/pencil/gophermega.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/pencil/gophermega.jpg
--------------------------------------------------------------------------------
/_content/doc/gopher/pencil/gopherrunning.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/pencil/gopherrunning.jpg
--------------------------------------------------------------------------------
/_content/doc/gopher/pencil/gopherswim.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/pencil/gopherswim.jpg
--------------------------------------------------------------------------------
/_content/doc/gopher/pencil/gopherswrench.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/pencil/gopherswrench.jpg
--------------------------------------------------------------------------------
/_content/doc/gopher/pkg.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/pkg.png
--------------------------------------------------------------------------------
/_content/doc/gopher/project.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/project.png
--------------------------------------------------------------------------------
/_content/doc/gopher/ref.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/ref.png
--------------------------------------------------------------------------------
/_content/doc/gopher/run.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/run.png
--------------------------------------------------------------------------------
/_content/doc/gopher/talks.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/gopher/talks.png
--------------------------------------------------------------------------------
/_content/doc/hats.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2021 The Go Authors. All rights reserved.
4 | * Use of this source code is governed by a BSD-style
5 | * license that can be found in the LICENSE file.
6 | */
7 |
8 | (function () {
9 | var cookieName = 'HaTS_BKT_DIST';
10 | var inBucket;
11 |
12 | var cookies = decodeURIComponent(document.cookie).split(';');
13 |
14 | for (let i = 0; i < cookies.length; i++) {
15 | var c = cookies[i];
16 |
17 | while (c.charAt(0) == ' ') {
18 | c = c.substring(1);
19 | }
20 |
21 | if (c.indexOf(cookieName + '=') == 0) {
22 | inBucket = c.substring((cookieName + '=').length, c.length);
23 | }
24 | }
25 |
26 | if (typeof inBucket === 'undefined') {
27 | inBucket = String(Math.random() < 0.01);
28 | document.cookie =
29 | cookieName + '=' + inBucket + '; path=/; max-age=2592000;';
30 | }
31 |
32 | if (inBucket === 'true') {
33 | document.cookie = cookieName + '=false ; path=/; max-age=2592000;';
34 |
35 | var tag = document.createElement('script');
36 | tag.src =
37 | 'https://www.gstatic.com/feedback/js/help/prod/service/lazy.min.js';
38 | tag.type = 'text/javascript';
39 | document.head.appendChild(tag);
40 |
41 | tag.onload = function () {
42 | var helpApi = window.help.service.Lazy.create(0, {
43 | apiKey: 'AIzaSyDfBPfajByU2G6RAjUf5sjkMSSLNTj7MMc',
44 | locale: 'en-US',
45 | });
46 |
47 | helpApi.requestSurvey({
48 | triggerId: 'dz6fkRxyz0njVvnD1rP0QxCXzhSX',
49 | callback: function (requestSurveyCallbackParam) {
50 | if (!requestSurveyCallbackParam.surveyData) {
51 | return;
52 | }
53 | helpApi.presentSurvey({
54 | surveyData: requestSurveyCallbackParam.surveyData,
55 | colorScheme: 1, // light
56 | customZIndex: 10000,
57 | });
58 | },
59 | });
60 | };
61 | }
62 | })();
63 |
--------------------------------------------------------------------------------
/_content/doc/help.html:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
70 | The Go Time podcast is a panel of Go experts and special guests
71 | discussing the Go programming language, the community, and everything in between.
72 |
Installing Go from source -- How to check out the sources, build them on your own machine, and run them.
13 |
14 |
15 |
Installing multiple Go versions
16 |
17 |
18 | You can install multiple Go versions on the same machine. For example, you might want to test your code on multiple Go versions. For a list of versions you can install this way, see the download page.
19 |
20 |
21 |
22 | Note: To install using the method described here, you'll need to have git installed.
23 |
24 |
25 |
26 | To install additional Go versions, run the go get command, specifying the download location of the version you want to install. The following example illustrates with version 1.10.7:
27 |
28 |
29 |
30 | $ go get golang.org/dl/go1.10.7
31 | $ go1.10.7 download
32 |
33 |
34 |
35 | To run go commands with the newly-downloaded version, append the version number to the go command, as follows:
36 |
37 |
38 |
39 | $ go1.10.7 version
40 | go version go1.10.7 linux/amd64
41 |
42 |
43 |
44 | When you have multiple versions installed, you can discover where each is installed, look at the version's GOROOT value. For example, run a command such as the following:
45 |
46 |
47 |
48 | $ go1.10.7 env GOROOT
49 |
50 |
51 |
52 | To uninstall a downloaded version, just remove the directory specified by its GOROOT environment variable and the goX.Y.Z binary.
53 |
54 |
55 |
Uninstalling Go
56 |
57 |
58 | You can remove Go from your system using the steps described in this topic.
59 |
60 |
61 |
Linux / macOS / FreeBSD
62 |
63 |
64 |
65 |
Delete the go directory.
66 |
67 |
68 | This is usually /usr/local/go.
69 |
70 |
71 |
72 |
73 |
Remove the Go bin directory from your PATH environment variable.
74 |
75 |
76 | Under Linux and FreeBSD, edit /etc/profile or $HOME/.profile. If you installed Go with the macOS package, remove the /etc/paths.d/go file.
77 |
78 |
79 |
80 |
81 |
82 |
83 |
Windows
84 |
85 |
86 | The simplest way to remove Go is via Add/Remove Programs in the Windows control panel:
87 |
88 |
89 |
90 |
91 |
In Control Panel, double-click Add/Remove Programs.
92 |
In Add/Remove Programs, select Go Programming Language, click Uninstall, then follow the prompts.
93 |
94 |
95 |
96 |
97 | For removing Go with tools, you can also use the command line:
98 |
99 |
100 |
101 |
102 |
Uninstall using the command line by running the following command:
103 |
104 |
109 |
110 | Note: Using this uninstall process for Windows will automatically remove windows environment variables created by the original installation.
111 |
112 |
113 |
114 |
115 |
116 |
117 |
--------------------------------------------------------------------------------
/_content/doc/modules/images/multiple-modules.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/modules/images/multiple-modules.png
--------------------------------------------------------------------------------
/_content/doc/modules/images/single-module.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/modules/images/single-module.png
--------------------------------------------------------------------------------
/_content/doc/modules/images/source-hierarchy.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/modules/images/source-hierarchy.png
--------------------------------------------------------------------------------
/_content/doc/modules/images/v2-branch-module.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/modules/images/v2-branch-module.png
--------------------------------------------------------------------------------
/_content/doc/modules/images/v2-module.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/modules/images/v2-module.png
--------------------------------------------------------------------------------
/_content/doc/modules/images/version-number.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/modules/images/version-number.png
--------------------------------------------------------------------------------
/_content/doc/modules/major-version.md:
--------------------------------------------------------------------------------
1 |
4 |
5 | You must update to a major version when changes you're making in a potential new
6 | version can't guarantee backward compatibility for the module's users. For
7 | example, you'll make this change if you change your module's public API such
8 | that it breaks client code using previous versions of the module.
9 |
10 | > **Note:** Each release type -- major, minor, patch, or pre-release -- has a
11 | different meaning for a module's users. Those users rely on these differences to
12 | understand the level of risk a release represents to their own code. In other
13 | words, when preparing a release, be sure that its version number accurately
14 | reflects the nature of the changes since the preceding release. For more on
15 | version numbers, see [Module version numbering](/doc/modules/version-numbers).
16 |
17 | **See also**
18 |
19 | * For an overview of module development, see [Developing and publishing
20 | modules](developing).
21 | * For an end-to-end view, see [Module release and versioning
22 | workflow](release-workflow).
23 |
24 | ## Considerations for a major version update {#considerations}
25 |
26 | You should only update to a new major version when it's absolutely necessary.
27 | A major version update represents significant churn for both you and your
28 | module's users. When you're considering a major version update, think about
29 | the following:
30 |
31 | * Be clear with your users about what releasing the new major version means
32 | for your support of previous major versions.
33 |
34 | Are previous versions deprecated? Supported as they were before? Will you be
35 | maintaining previous versions, including with bug fixes?
36 |
37 | * Be ready to take on the maintenance of two versions: the old and the new.
38 | For example, if you fix bugs in one, you'll often be porting those fixes into
39 | the other.
40 |
41 | * Remember that a new major version is a new module from a dependency management
42 | perspective. Your users will need to update to use a new module after you
43 | release, rather than simply upgrading.
44 |
45 | That's because a new major version has a different module path from the
46 | preceding major version. For example, for a module whose module path is
47 | example.com/mymodule, a v2 version would have the module path
48 | example.com/mymodule/v2.
49 |
50 | * When you're developing a new major version, you must also update import paths
51 | wherever code imports packages from the new module. Your module's users must
52 | also update their import paths if they want to upgrade to the new major version.
53 |
54 | ## Branching for a major release {#branching}
55 |
56 | The most straightforward approach to handling source when preparing to develop a
57 | new major version is to branch the repository at the latest version of the
58 | previous major version.
59 |
60 | For example, in a command prompt you might change to your module's root
61 | directory, then create a new v2 branch there.
62 |
63 | ```
64 | $ cd mymodule
65 | $ git checkout -b v2
66 | Switched to a new branch "v2"
67 | ```
68 |
69 |
72 |
73 |
74 | Once you have the source branched, you'll need to make the following changes to
75 | the source for your new version:
76 |
77 | * In the new version's go.mod file, append new major version number to the
78 | module path, as in the following example:
79 | * Existing version: `example.com/mymodule`
80 | * New version: `example.com/mymodule/v2`
81 |
82 | * In your Go code, update every imported package path where you import a package
83 | from the module, appending the major version number to the module path portion.
84 | * Old import statement: `import "example.com/mymodule/package1"`
85 | * New import statement: `import "example.com/mymodule/v2/package1"`
86 |
87 | For publishing steps, see [Publishing a module](/doc/modules/publishing).
88 |
--------------------------------------------------------------------------------
/_content/doc/modules/publishing.md:
--------------------------------------------------------------------------------
1 |
4 |
5 | When you want to make a module available for other developers, you publish it so
6 | that it's visible to Go tools. Once you've published the module, developers
7 | importing its packages will be able to resolve a dependency on the module by
8 | running commands such as `go get`.
9 |
10 | > **Note:** Don't change a tagged version of a module after publishing it. For
11 | developers using the module, Go tools authenticate a downloaded module against
12 | the first downloaded copy. If the two differ, Go tools will return a security
13 | error. Instead of changing the code for a previously published version, publish
14 | a new version.
15 |
16 | **See also**
17 |
18 | * For an overview of module development, see [Developing and publishing
19 | modules](developing)
20 | * For a high-level module development workflow -- which includes publishing --
21 | see [Module release and versioning workflow](release-workflow).
22 |
23 | ## Publishing steps
24 |
25 | Use the following steps to publish a module.
26 |
27 | 1. Open a command prompt and change to your module's root directory in the local
28 | repository.
29 |
30 | 1. Run `go mod tidy`, which removes any dependencies the module might have
31 | accumulated that are no longer necessary.
32 |
33 | ```
34 | $ go mod tidy
35 | ```
36 |
37 | 1. Run `go test ./...` a final time to make sure everything is working.
38 |
39 | This runs the unit tests you've written to use the Go testing framework.
40 |
41 | ```
42 | $ go test ./...
43 | ok example.com/mymodule 0.015s
44 | ```
45 |
46 | 1. Tag the project with a new version number using the `git tag` command.
47 |
48 | For the version number, use a number that signals to users the nature of
49 | changes in this release. For more, see [Module version
50 | numbering](version-numbers).
51 |
52 | ```
53 | $ git commit -m "mymodule: changes for v0.1.0"
54 | $ git tag v0.1.0
55 | ```
56 |
57 | 1. Push the new tag to the origin repository.
58 |
59 | ```
60 | $ git push origin v0.1.0
61 | ```
62 |
63 | 1. Make the module available by running the [`go list`
64 | command](https://golang.org/cmd/go/#hdr-List_packages_or_modules) to prompt
65 | Go to update its index of modules with information about the module you're
66 | publishing.
67 |
68 | Precede the command with a statement to set the `GOPROXY` environment
69 | variable to a Go proxy. This will ensure that your request reaches the
70 | proxy.
71 |
72 | ```
73 | $ GOPROXY=proxy.golang.org go list -m example.com/mymodule@v0.1.0
74 | ```
75 |
76 | Developers interested in your module import a package from it and run the [`go
77 | get` command]() just as they would with any other module. They can run the [`go
78 | get` command]() for latest versions or they can specify a particular version, as
79 | in the following example:
80 |
81 | ```
82 | $ go get example.com/mymodule@v0.1.0
83 | ```
84 |
--------------------------------------------------------------------------------
/_content/doc/play/fib.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // fib returns a function that returns
6 | // successive Fibonacci numbers.
7 | func fib() func() int {
8 | a, b := 0, 1
9 | return func() int {
10 | a, b = b, a+b
11 | return a
12 | }
13 | }
14 |
15 | func main() {
16 | f := fib()
17 | // Function calls are evaluated left-to-right.
18 | fmt.Println(f(), f(), f(), f(), f())
19 | }
20 |
--------------------------------------------------------------------------------
/_content/doc/play/hello.go:
--------------------------------------------------------------------------------
1 | // You can edit this code!
2 | // Click here and start typing.
3 | package main
4 |
5 | import "fmt"
6 |
7 | func main() {
8 | fmt.Println("Hello, 世界")
9 | }
10 |
--------------------------------------------------------------------------------
/_content/doc/play/life.go:
--------------------------------------------------------------------------------
1 | // An implementation of Conway's Game of Life.
2 | package main
3 |
4 | import (
5 | "bytes"
6 | "fmt"
7 | "math/rand"
8 | "time"
9 | )
10 |
11 | // Field represents a two-dimensional field of cells.
12 | type Field struct {
13 | s [][]bool
14 | w, h int
15 | }
16 |
17 | // NewField returns an empty field of the specified width and height.
18 | func NewField(w, h int) *Field {
19 | s := make([][]bool, h)
20 | for i := range s {
21 | s[i] = make([]bool, w)
22 | }
23 | return &Field{s: s, w: w, h: h}
24 | }
25 |
26 | // Set sets the state of the specified cell to the given value.
27 | func (f *Field) Set(x, y int, b bool) {
28 | f.s[y][x] = b
29 | }
30 |
31 | // Alive reports whether the specified cell is alive.
32 | // If the x or y coordinates are outside the field boundaries they are wrapped
33 | // toroidally. For instance, an x value of -1 is treated as width-1.
34 | func (f *Field) Alive(x, y int) bool {
35 | x += f.w
36 | x %= f.w
37 | y += f.h
38 | y %= f.h
39 | return f.s[y][x]
40 | }
41 |
42 | // Next returns the state of the specified cell at the next time step.
43 | func (f *Field) Next(x, y int) bool {
44 | // Count the adjacent cells that are alive.
45 | alive := 0
46 | for i := -1; i <= 1; i++ {
47 | for j := -1; j <= 1; j++ {
48 | if (j != 0 || i != 0) && f.Alive(x+i, y+j) {
49 | alive++
50 | }
51 | }
52 | }
53 | // Return next state according to the game rules:
54 | // exactly 3 neighbors: on,
55 | // exactly 2 neighbors: maintain current state,
56 | // otherwise: off.
57 | return alive == 3 || alive == 2 && f.Alive(x, y)
58 | }
59 |
60 | // Life stores the state of a round of Conway's Game of Life.
61 | type Life struct {
62 | a, b *Field
63 | w, h int
64 | }
65 |
66 | // NewLife returns a new Life game state with a random initial state.
67 | func NewLife(w, h int) *Life {
68 | a := NewField(w, h)
69 | for i := 0; i < (w * h / 4); i++ {
70 | a.Set(rand.Intn(w), rand.Intn(h), true)
71 | }
72 | return &Life{
73 | a: a, b: NewField(w, h),
74 | w: w, h: h,
75 | }
76 | }
77 |
78 | // Step advances the game by one instant, recomputing and updating all cells.
79 | func (l *Life) Step() {
80 | // Update the state of the next field (b) from the current field (a).
81 | for y := 0; y < l.h; y++ {
82 | for x := 0; x < l.w; x++ {
83 | l.b.Set(x, y, l.a.Next(x, y))
84 | }
85 | }
86 | // Swap fields a and b.
87 | l.a, l.b = l.b, l.a
88 | }
89 |
90 | // String returns the game board as a string.
91 | func (l *Life) String() string {
92 | var buf bytes.Buffer
93 | for y := 0; y < l.h; y++ {
94 | for x := 0; x < l.w; x++ {
95 | b := byte(' ')
96 | if l.a.Alive(x, y) {
97 | b = '*'
98 | }
99 | buf.WriteByte(b)
100 | }
101 | buf.WriteByte('\n')
102 | }
103 | return buf.String()
104 | }
105 |
106 | func main() {
107 | l := NewLife(40, 15)
108 | for i := 0; i < 300; i++ {
109 | l.Step()
110 | fmt.Print("\x0c", l) // Clear screen and print field.
111 | time.Sleep(time.Second / 30)
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/_content/doc/play/peano.go:
--------------------------------------------------------------------------------
1 | // Peano integers are represented by a linked
2 | // list whose nodes contain no data
3 | // (the nodes are the data).
4 | // http://en.wikipedia.org/wiki/Peano_axioms
5 |
6 | // This program demonstrates that Go's automatic
7 | // stack management can handle heavily recursive
8 | // computations.
9 |
10 | package main
11 |
12 | import "fmt"
13 |
14 | // Number is a pointer to a Number
15 | type Number *Number
16 |
17 | // The arithmetic value of a Number is the
18 | // count of the nodes comprising the list.
19 | // (See the count function below.)
20 |
21 | // -------------------------------------
22 | // Peano primitives
23 |
24 | func zero() *Number {
25 | return nil
26 | }
27 |
28 | func isZero(x *Number) bool {
29 | return x == nil
30 | }
31 |
32 | func add1(x *Number) *Number {
33 | e := new(Number)
34 | *e = x
35 | return e
36 | }
37 |
38 | func sub1(x *Number) *Number {
39 | return *x
40 | }
41 |
42 | func add(x, y *Number) *Number {
43 | if isZero(y) {
44 | return x
45 | }
46 | return add(add1(x), sub1(y))
47 | }
48 |
49 | func mul(x, y *Number) *Number {
50 | if isZero(x) || isZero(y) {
51 | return zero()
52 | }
53 | return add(mul(x, sub1(y)), x)
54 | }
55 |
56 | func fact(n *Number) *Number {
57 | if isZero(n) {
58 | return add1(zero())
59 | }
60 | return mul(fact(sub1(n)), n)
61 | }
62 |
63 | // -------------------------------------
64 | // Helpers to generate/count Peano integers
65 |
66 | func gen(n int) *Number {
67 | if n > 0 {
68 | return add1(gen(n - 1))
69 | }
70 | return zero()
71 | }
72 |
73 | func count(x *Number) int {
74 | if isZero(x) {
75 | return 0
76 | }
77 | return count(sub1(x)) + 1
78 | }
79 |
80 | // -------------------------------------
81 | // Print i! for i in [0,9]
82 |
83 | func main() {
84 | for i := 0; i <= 9; i++ {
85 | f := count(fact(gen(i)))
86 | fmt.Println(i, "! =", f)
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/_content/doc/play/pi.go:
--------------------------------------------------------------------------------
1 | // Concurrent computation of pi.
2 | // See https://goo.gl/la6Kli.
3 | //
4 | // This demonstrates Go's ability to handle
5 | // large numbers of concurrent processes.
6 | // It is an unreasonable way to calculate pi.
7 | package main
8 |
9 | import (
10 | "fmt"
11 | "math"
12 | )
13 |
14 | func main() {
15 | fmt.Println(pi(5000))
16 | }
17 |
18 | // pi launches n goroutines to compute an
19 | // approximation of pi.
20 | func pi(n int) float64 {
21 | ch := make(chan float64)
22 | for k := 0; k <= n; k++ {
23 | go term(ch, float64(k))
24 | }
25 | f := 0.0
26 | for k := 0; k <= n; k++ {
27 | f += <-ch
28 | }
29 | return f
30 | }
31 |
32 | func term(ch chan float64, k float64) {
33 | ch <- 4 * math.Pow(-1, k) / (2*k + 1)
34 | }
35 |
--------------------------------------------------------------------------------
/_content/doc/play/sieve.go:
--------------------------------------------------------------------------------
1 | // A concurrent prime sieve
2 |
3 | package main
4 |
5 | import "fmt"
6 |
7 | // Send the sequence 2, 3, 4, ... to channel 'ch'.
8 | func Generate(ch chan<- int) {
9 | for i := 2; ; i++ {
10 | ch <- i // Send 'i' to channel 'ch'.
11 | }
12 | }
13 |
14 | // Copy the values from channel 'in' to channel 'out',
15 | // removing those divisible by 'prime'.
16 | func Filter(in <-chan int, out chan<- int, prime int) {
17 | for {
18 | i := <-in // Receive value from 'in'.
19 | if i%prime != 0 {
20 | out <- i // Send 'i' to 'out'.
21 | }
22 | }
23 | }
24 |
25 | // The prime sieve: Daisy-chain Filter processes.
26 | func main() {
27 | ch := make(chan int) // Create a new channel.
28 | go Generate(ch) // Launch Generate goroutine.
29 | for i := 0; i < 10; i++ {
30 | prime := <-ch
31 | fmt.Println(prime)
32 | ch1 := make(chan int)
33 | go Filter(ch, ch1, prime)
34 | ch = ch1
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/_content/doc/play/solitaire.go:
--------------------------------------------------------------------------------
1 | // This program solves the (English) peg
2 | // solitaire board game.
3 | // http://en.wikipedia.org/wiki/Peg_solitaire
4 |
5 | package main
6 |
7 | import "fmt"
8 |
9 | const N = 11 + 1 // length of a row (+1 for \n)
10 |
11 | // The board must be surrounded by 2 illegal
12 | // fields in each direction so that move()
13 | // doesn't need to check the board boundaries.
14 | // Periods represent illegal fields,
15 | // ● are pegs, and ○ are holes.
16 |
17 | var board = []rune(
18 | `...........
19 | ...........
20 | ....●●●....
21 | ....●●●....
22 | ..●●●●●●●..
23 | ..●●●○●●●..
24 | ..●●●●●●●..
25 | ....●●●....
26 | ....●●●....
27 | ...........
28 | ...........
29 | `)
30 |
31 | // center is the position of the center hole if
32 | // there is a single one; otherwise it is -1.
33 | var center int
34 |
35 | func init() {
36 | n := 0
37 | for pos, field := range board {
38 | if field == '○' {
39 | center = pos
40 | n++
41 | }
42 | }
43 | if n != 1 {
44 | center = -1 // no single hole
45 | }
46 | }
47 |
48 | var moves int // number of times move is called
49 |
50 | // move tests if there is a peg at position pos that
51 | // can jump over another peg in direction dir. If the
52 | // move is valid, it is executed and move returns true.
53 | // Otherwise, move returns false.
54 | func move(pos, dir int) bool {
55 | moves++
56 | if board[pos] == '●' && board[pos+dir] == '●' && board[pos+2*dir] == '○' {
57 | board[pos] = '○'
58 | board[pos+dir] = '○'
59 | board[pos+2*dir] = '●'
60 | return true
61 | }
62 | return false
63 | }
64 |
65 | // unmove reverts a previously executed valid move.
66 | func unmove(pos, dir int) {
67 | board[pos] = '●'
68 | board[pos+dir] = '●'
69 | board[pos+2*dir] = '○'
70 | }
71 |
72 | // solve tries to find a sequence of moves such that
73 | // there is only one peg left at the end; if center is
74 | // >= 0, that last peg must be in the center position.
75 | // If a solution is found, solve prints the board after
76 | // each move in a backward fashion (i.e., the last
77 | // board position is printed first, all the way back to
78 | // the starting board position).
79 | func solve() bool {
80 | var last, n int
81 | for pos, field := range board {
82 | // try each board position
83 | if field == '●' {
84 | // found a peg
85 | for _, dir := range [...]int{-1, -N, +1, +N} {
86 | // try each direction
87 | if move(pos, dir) {
88 | // a valid move was found and executed,
89 | // see if this new board has a solution
90 | if solve() {
91 | unmove(pos, dir)
92 | fmt.Println(string(board))
93 | return true
94 | }
95 | unmove(pos, dir)
96 | }
97 | }
98 | last = pos
99 | n++
100 | }
101 | }
102 | // tried each possible move
103 | if n == 1 && (center < 0 || last == center) {
104 | // there's only one peg left
105 | fmt.Println(string(board))
106 | return true
107 | }
108 | // no solution found for this board
109 | return false
110 | }
111 |
112 | func main() {
113 | if !solve() {
114 | fmt.Println("no solution found")
115 | }
116 | fmt.Println(moves, "moves tried")
117 | }
118 |
--------------------------------------------------------------------------------
/_content/doc/play/tree.go:
--------------------------------------------------------------------------------
1 | // Go's concurrency primitives make it easy to
2 | // express concurrent concepts, such as
3 | // this binary tree comparison.
4 | //
5 | // Trees may be of different shapes,
6 | // but have the same contents. For example:
7 | //
8 | // 4 6
9 | // 2 6 4 7
10 | // 1 3 5 7 2 5
11 | // 1 3
12 | //
13 | // This program compares a pair of trees by
14 | // walking each in its own goroutine,
15 | // sending their contents through a channel
16 | // to a third goroutine that compares them.
17 |
18 | package main
19 |
20 | import (
21 | "fmt"
22 | "math/rand"
23 | )
24 |
25 | // A Tree is a binary tree with integer values.
26 | type Tree struct {
27 | Left *Tree
28 | Value int
29 | Right *Tree
30 | }
31 |
32 | // Walk traverses a tree depth-first,
33 | // sending each Value on a channel.
34 | func Walk(t *Tree, ch chan int) {
35 | if t == nil {
36 | return
37 | }
38 | Walk(t.Left, ch)
39 | ch <- t.Value
40 | Walk(t.Right, ch)
41 | }
42 |
43 | // Walker launches Walk in a new goroutine,
44 | // and returns a read-only channel of values.
45 | func Walker(t *Tree) <-chan int {
46 | ch := make(chan int)
47 | go func() {
48 | Walk(t, ch)
49 | close(ch)
50 | }()
51 | return ch
52 | }
53 |
54 | // Compare reads values from two Walkers
55 | // that run simultaneously, and returns true
56 | // if t1 and t2 have the same contents.
57 | func Compare(t1, t2 *Tree) bool {
58 | c1, c2 := Walker(t1), Walker(t2)
59 | for {
60 | v1, ok1 := <-c1
61 | v2, ok2 := <-c2
62 | if !ok1 || !ok2 {
63 | return ok1 == ok2
64 | }
65 | if v1 != v2 {
66 | break
67 | }
68 | }
69 | return false
70 | }
71 |
72 | // New returns a new, random binary tree
73 | // holding the values 1k, 2k, ..., nk.
74 | func New(n, k int) *Tree {
75 | var t *Tree
76 | for _, v := range rand.Perm(n) {
77 | t = insert(t, (1+v)*k)
78 | }
79 | return t
80 | }
81 |
82 | func insert(t *Tree, v int) *Tree {
83 | if t == nil {
84 | return &Tree{nil, v, nil}
85 | }
86 | if v < t.Value {
87 | t.Left = insert(t.Left, v)
88 | return t
89 | }
90 | t.Right = insert(t.Right, v)
91 | return t
92 | }
93 |
94 | func main() {
95 | t1 := New(100, 1)
96 | fmt.Println(Compare(t1, New(100, 1)), "Same Contents")
97 | fmt.Println(Compare(t1, New(99, 1)), "Differing Sizes")
98 | fmt.Println(Compare(t1, New(100, 2)), "Differing Values")
99 | fmt.Println(Compare(t1, New(101, 2)), "Dissimilar")
100 | }
101 |
--------------------------------------------------------------------------------
/_content/doc/progs/cgo1.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package rand
6 |
7 | /*
8 | #include
9 | */
10 | import "C"
11 |
12 | // STOP OMIT
13 | func Random() int {
14 | return int(C.rand())
15 | }
16 |
17 | // STOP OMIT
18 | func Seed(i int) {
19 | C.srand(C.uint(i))
20 | }
21 |
22 | // END OMIT
23 |
--------------------------------------------------------------------------------
/_content/doc/progs/cgo2.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package rand2
6 |
7 | /*
8 | #include
9 | */
10 | import "C"
11 |
12 | func Random() int {
13 | var r C.int = C.rand()
14 | return int(r)
15 | }
16 |
17 | // STOP OMIT
18 | func Seed(i int) {
19 | C.srand(C.uint(i))
20 | }
21 |
22 | // END OMIT
23 |
--------------------------------------------------------------------------------
/_content/doc/progs/cgo3.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package print
6 |
7 | // #include
8 | // #include
9 | import "C"
10 | import "unsafe"
11 |
12 | func Print(s string) {
13 | cs := C.CString(s)
14 | C.fputs(cs, (*C.FILE)(C.stdout))
15 | C.free(unsafe.Pointer(cs))
16 | }
17 |
18 | // END OMIT
19 |
--------------------------------------------------------------------------------
/_content/doc/progs/cgo4.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package print
6 |
7 | // #include
8 | // #include
9 | import "C"
10 | import "unsafe"
11 |
12 | func Print(s string) {
13 | cs := C.CString(s)
14 | defer C.free(unsafe.Pointer(cs))
15 | C.fputs(cs, (*C.FILE)(C.stdout))
16 | }
17 |
18 | // END OMIT
19 |
--------------------------------------------------------------------------------
/_content/doc/progs/defer.go:
--------------------------------------------------------------------------------
1 | // Copyright 2011 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | // This file contains the code snippets included in "Defer, Panic, and Recover."
6 |
7 | package main
8 |
9 | import (
10 | "fmt"
11 | "io"
12 | "os"
13 | )
14 |
15 | func a() {
16 | i := 0
17 | defer fmt.Println(i)
18 | i++
19 | return
20 | }
21 |
22 | // STOP OMIT
23 |
24 | func b() {
25 | for i := 0; i < 4; i++ {
26 | defer fmt.Print(i)
27 | }
28 | }
29 |
30 | // STOP OMIT
31 |
32 | func c() (i int) {
33 | defer func() { i++ }()
34 | return 1
35 | }
36 |
37 | // STOP OMIT
38 |
39 | // Initial version.
40 | func CopyFile(dstName, srcName string) (written int64, err error) {
41 | src, err := os.Open(srcName)
42 | if err != nil {
43 | return
44 | }
45 |
46 | dst, err := os.Create(dstName)
47 | if err != nil {
48 | return
49 | }
50 |
51 | written, err = io.Copy(dst, src)
52 | dst.Close()
53 | src.Close()
54 | return
55 | }
56 |
57 | // STOP OMIT
58 |
59 | func main() {
60 | a()
61 | b()
62 | fmt.Println()
63 | fmt.Println(c())
64 | }
65 |
--------------------------------------------------------------------------------
/_content/doc/progs/defer2.go:
--------------------------------------------------------------------------------
1 | // Copyright 2011 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | // This file contains the code snippets included in "Defer, Panic, and Recover."
6 |
7 | package main
8 |
9 | import "fmt"
10 | import "io" // OMIT
11 | import "os" // OMIT
12 |
13 | func main() {
14 | f()
15 | fmt.Println("Returned normally from f.")
16 | }
17 |
18 | func f() {
19 | defer func() {
20 | if r := recover(); r != nil {
21 | fmt.Println("Recovered in f", r)
22 | }
23 | }()
24 | fmt.Println("Calling g.")
25 | g(0)
26 | fmt.Println("Returned normally from g.")
27 | }
28 |
29 | func g(i int) {
30 | if i > 3 {
31 | fmt.Println("Panicking!")
32 | panic(fmt.Sprintf("%v", i))
33 | }
34 | defer fmt.Println("Defer in g", i)
35 | fmt.Println("Printing in g", i)
36 | g(i + 1)
37 | }
38 |
39 | // STOP OMIT
40 |
41 | // Revised version.
42 | func CopyFile(dstName, srcName string) (written int64, err error) {
43 | src, err := os.Open(srcName)
44 | if err != nil {
45 | return
46 | }
47 | defer src.Close()
48 |
49 | dst, err := os.Create(dstName)
50 | if err != nil {
51 | return
52 | }
53 | defer dst.Close()
54 |
55 | return io.Copy(dst, src)
56 | }
57 |
58 | // STOP OMIT
59 |
--------------------------------------------------------------------------------
/_content/doc/progs/eff_bytesize.go:
--------------------------------------------------------------------------------
1 | // Copyright 2009 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import "fmt"
8 |
9 | type ByteSize float64
10 |
11 | const (
12 | _ = iota // ignore first value by assigning to blank identifier
13 | KB ByteSize = 1 << (10 * iota)
14 | MB
15 | GB
16 | TB
17 | PB
18 | EB
19 | ZB
20 | YB
21 | )
22 |
23 | func (b ByteSize) String() string {
24 | switch {
25 | case b >= YB:
26 | return fmt.Sprintf("%.2fYB", b/YB)
27 | case b >= ZB:
28 | return fmt.Sprintf("%.2fZB", b/ZB)
29 | case b >= EB:
30 | return fmt.Sprintf("%.2fEB", b/EB)
31 | case b >= PB:
32 | return fmt.Sprintf("%.2fPB", b/PB)
33 | case b >= TB:
34 | return fmt.Sprintf("%.2fTB", b/TB)
35 | case b >= GB:
36 | return fmt.Sprintf("%.2fGB", b/GB)
37 | case b >= MB:
38 | return fmt.Sprintf("%.2fMB", b/MB)
39 | case b >= KB:
40 | return fmt.Sprintf("%.2fKB", b/KB)
41 | }
42 | return fmt.Sprintf("%.2fB", b)
43 | }
44 |
45 | func main() {
46 | fmt.Println(YB, ByteSize(1e13))
47 | }
48 |
--------------------------------------------------------------------------------
/_content/doc/progs/eff_qr.go:
--------------------------------------------------------------------------------
1 | // Copyright 2009 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "flag"
9 | "html/template"
10 | "log"
11 | "net/http"
12 | )
13 |
14 | var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18
15 |
16 | var templ = template.Must(template.New("qr").Parse(templateStr))
17 |
18 | func main() {
19 | flag.Parse()
20 | http.Handle("/", http.HandlerFunc(QR))
21 | err := http.ListenAndServe(*addr, nil)
22 | if err != nil {
23 | log.Fatal("ListenAndServe:", err)
24 | }
25 | }
26 |
27 | func QR(w http.ResponseWriter, req *http.Request) {
28 | templ.Execute(w, req.FormValue("s"))
29 | }
30 |
31 | const templateStr = `
32 |
33 |
34 | QR Link Generator
35 |
36 |
37 | {{if .}}
38 |
39 |
40 | {{.}}
41 |
42 |
43 | {{end}}
44 |
48 |
49 |
50 | `
51 |
--------------------------------------------------------------------------------
/_content/doc/progs/eff_sequence.go:
--------------------------------------------------------------------------------
1 | // Copyright 2009 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "fmt"
9 | "sort"
10 | )
11 |
12 | func main() {
13 | seq := Sequence{6, 2, -1, 44, 16}
14 | sort.Sort(seq)
15 | fmt.Println(seq)
16 | }
17 |
18 | type Sequence []int
19 |
20 | // Methods required by sort.Interface.
21 | func (s Sequence) Len() int {
22 | return len(s)
23 | }
24 | func (s Sequence) Less(i, j int) bool {
25 | return s[i] < s[j]
26 | }
27 | func (s Sequence) Swap(i, j int) {
28 | s[i], s[j] = s[j], s[i]
29 | }
30 |
31 | // Copy returns a copy of the Sequence.
32 | func (s Sequence) Copy() Sequence {
33 | copy := make(Sequence, 0, len(s))
34 | return append(copy, s...)
35 | }
36 |
37 | // Method for printing - sorts the elements before printing.
38 | func (s Sequence) String() string {
39 | s = s.Copy() // Make a copy; don't overwrite argument.
40 | sort.Sort(s)
41 | str := "["
42 | for i, elem := range s { // Loop is O(N²); will fix that in next example.
43 | if i > 0 {
44 | str += " "
45 | }
46 | str += fmt.Sprint(elem)
47 | }
48 | return str + "]"
49 | }
50 |
--------------------------------------------------------------------------------
/_content/doc/progs/eff_unused1.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "io"
6 | "log"
7 | "os"
8 | )
9 |
10 | func main() {
11 | fd, err := os.Open("test.go")
12 | if err != nil {
13 | log.Fatal(err)
14 | }
15 | // TODO: use fd.
16 | }
17 |
--------------------------------------------------------------------------------
/_content/doc/progs/eff_unused2.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "io"
6 | "log"
7 | "os"
8 | )
9 |
10 | var _ = fmt.Printf // For debugging; delete when done.
11 | var _ io.Reader // For debugging; delete when done.
12 |
13 | func main() {
14 | fd, err := os.Open("test.go")
15 | if err != nil {
16 | log.Fatal(err)
17 | }
18 | // TODO: use fd.
19 | _ = fd
20 | }
21 |
--------------------------------------------------------------------------------
/_content/doc/progs/error.go:
--------------------------------------------------------------------------------
1 | // Copyright 2011 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | // This file contains the code snippets included in "Error Handling and Go."
6 |
7 | package main
8 |
9 | import (
10 | "encoding/json"
11 | "errors"
12 | "fmt"
13 | "log"
14 | "net"
15 | "os"
16 | "time"
17 | )
18 |
19 | type File struct{}
20 |
21 | func Open(name string) (file *File, err error) {
22 | // OMIT
23 | panic(1)
24 | // STOP OMIT
25 | }
26 |
27 | func openFile() { // OMIT
28 | f, err := os.Open("filename.ext")
29 | if err != nil {
30 | log.Fatal(err)
31 | }
32 | // do something with the open *File f
33 | // STOP OMIT
34 | _ = f
35 | }
36 |
37 | // errorString is a trivial implementation of error.
38 | type errorString struct {
39 | s string
40 | }
41 |
42 | func (e *errorString) Error() string {
43 | return e.s
44 | }
45 |
46 | // STOP OMIT
47 |
48 | // New returns an error that formats as the given text.
49 | func New(text string) error {
50 | return &errorString{text}
51 | }
52 |
53 | // STOP OMIT
54 |
55 | func Sqrt(f float64) (float64, error) {
56 | if f < 0 {
57 | return 0, errors.New("math: square root of negative number")
58 | }
59 | // implementation
60 | return 0, nil // OMIT
61 | }
62 |
63 | // STOP OMIT
64 |
65 | func printErr() (int, error) { // OMIT
66 | f, err := Sqrt(-1)
67 | if err != nil {
68 | fmt.Println(err)
69 | }
70 | // STOP OMIT
71 | // fmtError OMIT
72 | if f < 0 {
73 | return 0, fmt.Errorf("math: square root of negative number %g", f)
74 | }
75 | // STOP OMIT
76 | return 0, nil
77 | }
78 |
79 | type NegativeSqrtError float64
80 |
81 | func (f NegativeSqrtError) Error() string {
82 | return fmt.Sprintf("math: square root of negative number %g", float64(f))
83 | }
84 |
85 | // STOP OMIT
86 |
87 | type SyntaxError struct {
88 | msg string // description of error
89 | Offset int64 // error occurred after reading Offset bytes
90 | }
91 |
92 | func (e *SyntaxError) Error() string { return e.msg }
93 |
94 | // STOP OMIT
95 |
96 | func decodeError(dec *json.Decoder, val struct{}) error { // OMIT
97 | var f os.FileInfo // OMIT
98 | if err := dec.Decode(&val); err != nil {
99 | if serr, ok := err.(*json.SyntaxError); ok {
100 | line, col := findLine(f, serr.Offset)
101 | return fmt.Errorf("%s:%d:%d: %v", f.Name(), line, col, err)
102 | }
103 | return err
104 | }
105 | // STOP OMIT
106 | return nil
107 | }
108 |
109 | func findLine(os.FileInfo, int64) (int, int) {
110 | // place holder; no need to run
111 | return 0, 0
112 | }
113 |
114 | func netError(err error) { // OMIT
115 | for { // OMIT
116 | if nerr, ok := err.(net.Error); ok && nerr.Temporary() {
117 | time.Sleep(1e9)
118 | continue
119 | }
120 | if err != nil {
121 | log.Fatal(err)
122 | }
123 | // STOP OMIT
124 | }
125 | }
126 |
127 | func main() {}
128 |
--------------------------------------------------------------------------------
/_content/doc/progs/error2.go:
--------------------------------------------------------------------------------
1 | // Copyright 2011 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | // This file contains the code snippets included in "Error Handling and Go."
6 |
7 | package main
8 |
9 | import (
10 | "net/http"
11 | "text/template"
12 | )
13 |
14 | func init() {
15 | http.HandleFunc("/view", viewRecord)
16 | }
17 |
18 | func viewRecord(w http.ResponseWriter, r *http.Request) {
19 | c := appengine.NewContext(r)
20 | key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil)
21 | record := new(Record)
22 | if err := datastore.Get(c, key, record); err != nil {
23 | http.Error(w, err.Error(), http.StatusInternalServerError)
24 | return
25 | }
26 | if err := viewTemplate.Execute(w, record); err != nil {
27 | http.Error(w, err.Error(), http.StatusInternalServerError)
28 | }
29 | }
30 |
31 | // STOP OMIT
32 |
33 | type ap struct{}
34 |
35 | func (ap) NewContext(*http.Request) *ctx { return nil }
36 |
37 | type ctx struct{}
38 |
39 | func (*ctx) Errorf(string, ...interface{}) {}
40 |
41 | var appengine ap
42 |
43 | type ds struct{}
44 |
45 | func (ds) NewKey(*ctx, string, string, int, *int) string { return "" }
46 | func (ds) Get(*ctx, string, *Record) error { return nil }
47 |
48 | var datastore ds
49 |
50 | type Record struct{}
51 |
52 | var viewTemplate *template.Template
53 |
54 | func main() {}
55 |
--------------------------------------------------------------------------------
/_content/doc/progs/error3.go:
--------------------------------------------------------------------------------
1 | // Copyright 2011 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | // This file contains the code snippets included in "Error Handling and Go."
6 |
7 | package main
8 |
9 | import (
10 | "net/http"
11 | "text/template"
12 | )
13 |
14 | func init() {
15 | http.Handle("/view", appHandler(viewRecord))
16 | }
17 |
18 | // STOP OMIT
19 |
20 | func viewRecord(w http.ResponseWriter, r *http.Request) error {
21 | c := appengine.NewContext(r)
22 | key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil)
23 | record := new(Record)
24 | if err := datastore.Get(c, key, record); err != nil {
25 | return err
26 | }
27 | return viewTemplate.Execute(w, record)
28 | }
29 |
30 | // STOP OMIT
31 |
32 | type appHandler func(http.ResponseWriter, *http.Request) error
33 |
34 | func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
35 | if err := fn(w, r); err != nil {
36 | http.Error(w, err.Error(), http.StatusInternalServerError)
37 | }
38 | }
39 |
40 | // STOP OMIT
41 |
42 | type ap struct{}
43 |
44 | func (ap) NewContext(*http.Request) *ctx { return nil }
45 |
46 | type ctx struct{}
47 |
48 | func (*ctx) Errorf(string, ...interface{}) {}
49 |
50 | var appengine ap
51 |
52 | type ds struct{}
53 |
54 | func (ds) NewKey(*ctx, string, string, int, *int) string { return "" }
55 | func (ds) Get(*ctx, string, *Record) error { return nil }
56 |
57 | var datastore ds
58 |
59 | type Record struct{}
60 |
61 | var viewTemplate *template.Template
62 |
63 | func main() {}
64 |
--------------------------------------------------------------------------------
/_content/doc/progs/error4.go:
--------------------------------------------------------------------------------
1 | // Copyright 2011 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | // This file contains the code snippets included in "Error Handling and Go."
6 |
7 | package main
8 |
9 | import (
10 | "net/http"
11 | "text/template"
12 | )
13 |
14 | type appError struct {
15 | Error error
16 | Message string
17 | Code int
18 | }
19 |
20 | // STOP OMIT
21 |
22 | type appHandler func(http.ResponseWriter, *http.Request) *appError
23 |
24 | func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
25 | if e := fn(w, r); e != nil { // e is *appError, not error.
26 | c := appengine.NewContext(r)
27 | c.Errorf("%v", e.Error)
28 | http.Error(w, e.Message, e.Code)
29 | }
30 | }
31 |
32 | // STOP OMIT
33 |
34 | func viewRecord(w http.ResponseWriter, r *http.Request) *appError {
35 | c := appengine.NewContext(r)
36 | key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil)
37 | record := new(Record)
38 | if err := datastore.Get(c, key, record); err != nil {
39 | return &appError{err, "Record not found", 404}
40 | }
41 | if err := viewTemplate.Execute(w, record); err != nil {
42 | return &appError{err, "Can't display record", 500}
43 | }
44 | return nil
45 | }
46 |
47 | // STOP OMIT
48 |
49 | func init() {
50 | http.Handle("/view", appHandler(viewRecord))
51 | }
52 |
53 | type ap struct{}
54 |
55 | func (ap) NewContext(*http.Request) *ctx { return nil }
56 |
57 | type ctx struct{}
58 |
59 | func (*ctx) Errorf(string, ...interface{}) {}
60 |
61 | var appengine ap
62 |
63 | type ds struct{}
64 |
65 | func (ds) NewKey(*ctx, string, string, int, *int) string { return "" }
66 | func (ds) Get(*ctx, string, *Record) error { return nil }
67 |
68 | var datastore ds
69 |
70 | type Record struct{}
71 |
72 | var viewTemplate *template.Template
73 |
74 | func main() {}
75 |
--------------------------------------------------------------------------------
/_content/doc/progs/gobs1.go:
--------------------------------------------------------------------------------
1 | // Copyright 2011 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package gobs1
6 |
7 | type T struct{ X, Y, Z int } // Only exported fields are encoded and decoded.
8 | var t = T{X: 7, Y: 0, Z: 8}
9 |
10 | // STOP OMIT
11 |
12 | type U struct{ X, Y *int8 } // Note: pointers to int8s
13 | var u U
14 |
15 | // STOP OMIT
16 |
17 | type Node struct {
18 | Value int
19 | Left, Right *Node
20 | }
21 |
22 | // STOP OMIT
23 |
--------------------------------------------------------------------------------
/_content/doc/progs/gobs2.go:
--------------------------------------------------------------------------------
1 | // Copyright 2011 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "bytes"
9 | "encoding/gob"
10 | "fmt"
11 | "log"
12 | )
13 |
14 | type P struct {
15 | X, Y, Z int
16 | Name string
17 | }
18 |
19 | type Q struct {
20 | X, Y *int32
21 | Name string
22 | }
23 |
24 | func main() {
25 | // Initialize the encoder and decoder. Normally enc and dec would be
26 | // bound to network connections and the encoder and decoder would
27 | // run in different processes.
28 | var network bytes.Buffer // Stand-in for a network connection
29 | enc := gob.NewEncoder(&network) // Will write to network.
30 | dec := gob.NewDecoder(&network) // Will read from network.
31 | // Encode (send) the value.
32 | err := enc.Encode(P{3, 4, 5, "Pythagoras"})
33 | if err != nil {
34 | log.Fatal("encode error:", err)
35 | }
36 | // Decode (receive) the value.
37 | var q Q
38 | err = dec.Decode(&q)
39 | if err != nil {
40 | log.Fatal("decode error:", err)
41 | }
42 | fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y)
43 | }
44 |
--------------------------------------------------------------------------------
/_content/doc/progs/image_draw.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | // This file contains the code snippets included in "The Go image/draw package."
6 |
7 | package main
8 |
9 | import (
10 | "image"
11 | "image/color"
12 | "image/draw"
13 | )
14 |
15 | func main() {
16 | Color()
17 | Rect()
18 | RectAndScroll()
19 | ConvAndCircle()
20 | Glyph()
21 | }
22 |
23 | func Color() {
24 | c := color.RGBA{255, 0, 255, 255}
25 | r := image.Rect(0, 0, 640, 480)
26 | dst := image.NewRGBA(r)
27 |
28 | // ZERO OMIT
29 | // image.ZP is the zero point -- the origin.
30 | draw.Draw(dst, r, &image.Uniform{c}, image.ZP, draw.Src)
31 | // STOP OMIT
32 |
33 | // BLUE OMIT
34 | m := image.NewRGBA(image.Rect(0, 0, 640, 480))
35 | blue := color.RGBA{0, 0, 255, 255}
36 | draw.Draw(m, m.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src)
37 | // STOP OMIT
38 |
39 | // RESET OMIT
40 | draw.Draw(m, m.Bounds(), image.Transparent, image.ZP, draw.Src)
41 | // STOP OMIT
42 | }
43 |
44 | func Rect() {
45 | dst := image.NewRGBA(image.Rect(0, 0, 640, 480))
46 | sr := image.Rect(0, 0, 200, 200)
47 | src := image.Black
48 | dp := image.Point{100, 100}
49 |
50 | // RECT OMIT
51 | r := image.Rectangle{dp, dp.Add(sr.Size())}
52 | draw.Draw(dst, r, src, sr.Min, draw.Src)
53 | // STOP OMIT
54 | }
55 |
56 | func RectAndScroll() {
57 | dst := image.NewRGBA(image.Rect(0, 0, 640, 480))
58 | sr := image.Rect(0, 0, 200, 200)
59 | src := image.Black
60 | dp := image.Point{100, 100}
61 |
62 | // RECT2 OMIT
63 | r := sr.Sub(sr.Min).Add(dp)
64 | draw.Draw(dst, r, src, sr.Min, draw.Src)
65 | // STOP OMIT
66 |
67 | m := dst
68 |
69 | // SCROLL OMIT
70 | b := m.Bounds()
71 | p := image.Pt(0, 20)
72 | // Note that even though the second argument is b,
73 | // the effective rectangle is smaller due to clipping.
74 | draw.Draw(m, b, m, b.Min.Add(p), draw.Src)
75 | dirtyRect := b.Intersect(image.Rect(b.Min.X, b.Max.Y-20, b.Max.X, b.Max.Y))
76 | // STOP OMIT
77 |
78 | _ = dirtyRect // noop
79 | }
80 |
81 | func ConvAndCircle() {
82 | src := image.NewRGBA(image.Rect(0, 0, 640, 480))
83 | dst := image.NewRGBA(image.Rect(0, 0, 640, 480))
84 |
85 | // CONV OMIT
86 | b := src.Bounds()
87 | m := image.NewRGBA(b)
88 | draw.Draw(m, b, src, b.Min, draw.Src)
89 | // STOP OMIT
90 |
91 | p := image.Point{100, 100}
92 | r := 50
93 |
94 | // CIRCLE2 OMIT
95 | draw.DrawMask(dst, dst.Bounds(), src, image.ZP, &circle{p, r}, image.ZP, draw.Over)
96 | // STOP OMIT
97 | }
98 |
99 | func theGlyphImageForAFont() image.Image {
100 | return image.NewRGBA(image.Rect(0, 0, 640, 480))
101 | }
102 |
103 | func theBoundsFor(index int) image.Rectangle {
104 | return image.Rect(0, 0, 32, 32)
105 | }
106 |
107 | func Glyph() {
108 | p := image.Point{100, 100}
109 | dst := image.NewRGBA(image.Rect(0, 0, 640, 480))
110 | glyphIndex := 42
111 |
112 | // GLYPH OMIT
113 | src := &image.Uniform{color.RGBA{0, 0, 255, 255}}
114 | mask := theGlyphImageForAFont()
115 | mr := theBoundsFor(glyphIndex)
116 | draw.DrawMask(dst, mr.Sub(mr.Min).Add(p), src, image.ZP, mask, mr.Min, draw.Over)
117 | // STOP OMIT
118 | }
119 |
120 | //CIRCLESTRUCT OMIT
121 | type circle struct {
122 | p image.Point
123 | r int
124 | }
125 |
126 | func (c *circle) ColorModel() color.Model {
127 | return color.AlphaModel
128 | }
129 |
130 | func (c *circle) Bounds() image.Rectangle {
131 | return image.Rect(c.p.X-c.r, c.p.Y-c.r, c.p.X+c.r, c.p.Y+c.r)
132 | }
133 |
134 | func (c *circle) At(x, y int) color.Color {
135 | xx, yy, rr := float64(x-c.p.X)+0.5, float64(y-c.p.Y)+0.5, float64(c.r)
136 | if xx*xx+yy*yy < rr*rr {
137 | return color.Alpha{255}
138 | }
139 | return color.Alpha{0}
140 | }
141 |
142 | //STOP OMIT
143 |
--------------------------------------------------------------------------------
/_content/doc/progs/image_package1.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "fmt"
9 | "image"
10 | )
11 |
12 | func main() {
13 | p := image.Point{2, 1}
14 | fmt.Println("X is", p.X, "Y is", p.Y)
15 | }
16 |
--------------------------------------------------------------------------------
/_content/doc/progs/image_package2.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "fmt"
9 | "image"
10 | )
11 |
12 | func main() {
13 | r := image.Rect(2, 1, 5, 5)
14 | // Dx and Dy return a rectangle's width and height.
15 | fmt.Println(r.Dx(), r.Dy(), image.Pt(0, 0).In(r)) // prints 3 4 false
16 | }
17 |
--------------------------------------------------------------------------------
/_content/doc/progs/image_package3.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "fmt"
9 | "image"
10 | )
11 |
12 | func main() {
13 | r := image.Rect(2, 1, 5, 5).Add(image.Pt(-4, -2))
14 | fmt.Println(r.Dx(), r.Dy(), image.Pt(0, 0).In(r)) // prints 3 4 true
15 | }
16 |
--------------------------------------------------------------------------------
/_content/doc/progs/image_package4.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "fmt"
9 | "image"
10 | )
11 |
12 | func main() {
13 | r := image.Rect(0, 0, 4, 3).Intersect(image.Rect(2, 2, 5, 5))
14 | // Size returns a rectangle's width and height, as a Point.
15 | fmt.Printf("%#v\n", r.Size()) // prints image.Point{X:2, Y:1}
16 | }
17 |
--------------------------------------------------------------------------------
/_content/doc/progs/image_package5.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "fmt"
9 | "image"
10 | "image/color"
11 | )
12 |
13 | func main() {
14 | m := image.NewRGBA(image.Rect(0, 0, 640, 480))
15 | m.Set(5, 5, color.RGBA{255, 0, 0, 255})
16 | fmt.Println(m.At(5, 5))
17 | }
18 |
--------------------------------------------------------------------------------
/_content/doc/progs/image_package6.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "fmt"
9 | "image"
10 | )
11 |
12 | func main() {
13 | m0 := image.NewRGBA(image.Rect(0, 0, 8, 5))
14 | m1 := m0.SubImage(image.Rect(1, 2, 5, 5)).(*image.RGBA)
15 | fmt.Println(m0.Bounds().Dx(), m1.Bounds().Dx()) // prints 8, 4
16 | fmt.Println(m0.Stride == m1.Stride) // prints true
17 | }
18 |
--------------------------------------------------------------------------------
/_content/doc/progs/interface.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | // This file contains the code snippets included in "The Laws of Reflection."
6 |
7 | package main
8 |
9 | import (
10 | "bufio"
11 | "bytes"
12 | "io"
13 | "os"
14 | )
15 |
16 | type MyInt int
17 |
18 | var i int
19 | var j MyInt
20 |
21 | // STOP OMIT
22 |
23 | // Reader is the interface that wraps the basic Read method.
24 | type Reader interface {
25 | Read(p []byte) (n int, err error)
26 | }
27 |
28 | // Writer is the interface that wraps the basic Write method.
29 | type Writer interface {
30 | Write(p []byte) (n int, err error)
31 | }
32 |
33 | // STOP OMIT
34 |
35 | func readers() { // OMIT
36 | var r io.Reader
37 | r = os.Stdin
38 | r = bufio.NewReader(r)
39 | r = new(bytes.Buffer)
40 | // and so on
41 | // STOP OMIT
42 | }
43 |
44 | func typeAssertions() (interface{}, error) { // OMIT
45 | var r io.Reader
46 | tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
47 | if err != nil {
48 | return nil, err
49 | }
50 | r = tty
51 | // STOP OMIT
52 | var w io.Writer
53 | w = r.(io.Writer)
54 | // STOP OMIT
55 | var empty interface{}
56 | empty = w
57 | // STOP OMIT
58 | return empty, err
59 | }
60 |
61 | func main() {
62 | }
63 |
--------------------------------------------------------------------------------
/_content/doc/progs/interface2.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | // This file contains the code snippets included in "The Laws of Reflection."
6 |
7 | package main
8 |
9 | import (
10 | "fmt"
11 | "reflect"
12 | )
13 |
14 | func main() {
15 | var x float64 = 3.4
16 | fmt.Println("type:", reflect.TypeOf(x))
17 | // STOP OMIT
18 | // TODO(proppy): test output OMIT
19 | }
20 |
21 | // STOP main OMIT
22 |
23 | func f1() {
24 | // START f1 OMIT
25 | var x float64 = 3.4
26 | v := reflect.ValueOf(x)
27 | fmt.Println("type:", v.Type())
28 | fmt.Println("kind is float64:", v.Kind() == reflect.Float64)
29 | fmt.Println("value:", v.Float())
30 | // STOP OMIT
31 | }
32 |
33 | func f2() {
34 | // START f2 OMIT
35 | var x uint8 = 'x'
36 | v := reflect.ValueOf(x)
37 | fmt.Println("type:", v.Type()) // uint8.
38 | fmt.Println("kind is uint8: ", v.Kind() == reflect.Uint8) // true.
39 | x = uint8(v.Uint()) // v.Uint returns a uint64.
40 | // STOP OMIT
41 | }
42 |
43 | func f3() {
44 | // START f3 OMIT
45 | type MyInt int
46 | var x MyInt = 7
47 | v := reflect.ValueOf(x)
48 | // STOP OMIT
49 | // START f3b OMIT
50 | y := v.Interface().(float64) // y will have type float64.
51 | fmt.Println(y)
52 | // STOP OMIT
53 | // START f3c OMIT
54 | fmt.Println(v.Interface())
55 | // STOP OMIT
56 | // START f3d OMIT
57 | fmt.Printf("value is %7.1e\n", v.Interface())
58 | // STOP OMIT
59 | }
60 |
61 | func f4() {
62 | // START f4 OMIT
63 | var x float64 = 3.4
64 | v := reflect.ValueOf(x)
65 | v.SetFloat(7.1) // Error: will panic.
66 | // STOP OMIT
67 | }
68 |
69 | func f5() {
70 | // START f5 OMIT
71 | var x float64 = 3.4
72 | v := reflect.ValueOf(x)
73 | fmt.Println("settability of v:", v.CanSet())
74 | // STOP OMIT
75 | }
76 |
77 | func f6() {
78 | // START f6 OMIT
79 | var x float64 = 3.4
80 | v := reflect.ValueOf(x)
81 | // STOP OMIT
82 | // START f6b OMIT
83 | v.SetFloat(7.1)
84 | // STOP OMIT
85 | }
86 |
87 | func f7() {
88 | // START f7 OMIT
89 | var x float64 = 3.4
90 | p := reflect.ValueOf(&x) // Note: take the address of x.
91 | fmt.Println("type of p:", p.Type())
92 | fmt.Println("settability of p:", p.CanSet())
93 | // STOP OMIT
94 | // START f7b OMIT
95 | v := p.Elem()
96 | fmt.Println("settability of v:", v.CanSet())
97 | // STOP OMIT
98 | // START f7c OMIT
99 | v.SetFloat(7.1)
100 | fmt.Println(v.Interface())
101 | fmt.Println(x)
102 | // STOP OMIT
103 | }
104 |
105 | func f8() {
106 | // START f8 OMIT
107 | type T struct {
108 | A int
109 | B string
110 | }
111 | t := T{23, "skidoo"}
112 | s := reflect.ValueOf(&t).Elem()
113 | typeOfT := s.Type()
114 | for i := 0; i < s.NumField(); i++ {
115 | f := s.Field(i)
116 | fmt.Printf("%d: %s %s = %v\n", i,
117 | typeOfT.Field(i).Name, f.Type(), f.Interface())
118 | }
119 | // STOP OMIT
120 | // START f8b OMIT
121 | s.Field(0).SetInt(77)
122 | s.Field(1).SetString("Sunset Strip")
123 | fmt.Println("t is now", t)
124 | // STOP OMIT
125 | }
126 |
127 | func f9() {
128 | // START f9 OMIT
129 | var x float64 = 3.4
130 | fmt.Println("value:", reflect.ValueOf(x))
131 | // STOP OMIT
132 | }
133 |
--------------------------------------------------------------------------------
/_content/doc/progs/json1.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "encoding/json"
9 | "log"
10 | "reflect"
11 | )
12 |
13 | type Message struct {
14 | Name string
15 | Body string
16 | Time int64
17 | }
18 |
19 | // STOP OMIT
20 |
21 | func Encode() {
22 | m := Message{"Alice", "Hello", 1294706395881547000}
23 | b, err := json.Marshal(m)
24 |
25 | if err != nil {
26 | panic(err)
27 | }
28 |
29 | expected := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`)
30 | if !reflect.DeepEqual(b, expected) {
31 | log.Panicf("Error marshaling %q, expected %q, got %q.", m, expected, b)
32 | }
33 |
34 | }
35 |
36 | func Decode() {
37 | b := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`)
38 | var m Message
39 | err := json.Unmarshal(b, &m)
40 |
41 | if err != nil {
42 | panic(err)
43 | }
44 |
45 | expected := Message{
46 | Name: "Alice",
47 | Body: "Hello",
48 | Time: 1294706395881547000,
49 | }
50 |
51 | if !reflect.DeepEqual(m, expected) {
52 | log.Panicf("Error unmarshaling %q, expected %q, got %q.", b, expected, m)
53 | }
54 |
55 | m = Message{
56 | Name: "Alice",
57 | Body: "Hello",
58 | Time: 1294706395881547000,
59 | }
60 |
61 | // STOP OMIT
62 | }
63 |
64 | func PartialDecode() {
65 | b := []byte(`{"Name":"Bob","Food":"Pickle"}`)
66 | var m Message
67 | err := json.Unmarshal(b, &m)
68 |
69 | // STOP OMIT
70 |
71 | if err != nil {
72 | panic(err)
73 | }
74 |
75 | expected := Message{
76 | Name: "Bob",
77 | }
78 |
79 | if !reflect.DeepEqual(expected, m) {
80 | log.Panicf("Error unmarshaling %q, expected %q, got %q.", b, expected, m)
81 | }
82 | }
83 |
84 | func main() {
85 | Encode()
86 | Decode()
87 | PartialDecode()
88 | }
89 |
--------------------------------------------------------------------------------
/_content/doc/progs/json2.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "fmt"
9 | "math"
10 | )
11 |
12 | func InterfaceExample() {
13 | var i interface{}
14 | i = "a string"
15 | i = 2011
16 | i = 2.777
17 |
18 | // STOP OMIT
19 |
20 | r := i.(float64)
21 | fmt.Println("the circle's area", math.Pi*r*r)
22 |
23 | // STOP OMIT
24 |
25 | switch v := i.(type) {
26 | case int:
27 | fmt.Println("twice i is", v*2)
28 | case float64:
29 | fmt.Println("the reciprocal of i is", 1/v)
30 | case string:
31 | h := len(v) / 2
32 | fmt.Println("i swapped by halves is", v[h:]+v[:h])
33 | default:
34 | // i isn't one of the types above
35 | }
36 |
37 | // STOP OMIT
38 | }
39 |
40 | func main() {
41 | InterfaceExample()
42 | }
43 |
--------------------------------------------------------------------------------
/_content/doc/progs/json3.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "encoding/json"
9 | "fmt"
10 | "log"
11 | "reflect"
12 | )
13 |
14 | func Decode() {
15 | b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
16 |
17 | var f interface{}
18 | err := json.Unmarshal(b, &f)
19 |
20 | // STOP OMIT
21 |
22 | if err != nil {
23 | panic(err)
24 | }
25 |
26 | expected := map[string]interface{}{
27 | "Name": "Wednesday",
28 | "Age": float64(6),
29 | "Parents": []interface{}{
30 | "Gomez",
31 | "Morticia",
32 | },
33 | }
34 |
35 | if !reflect.DeepEqual(f, expected) {
36 | log.Panicf("Error unmarshaling %q, expected %q, got %q", b, expected, f)
37 | }
38 |
39 | f = map[string]interface{}{
40 | "Name": "Wednesday",
41 | "Age": 6,
42 | "Parents": []interface{}{
43 | "Gomez",
44 | "Morticia",
45 | },
46 | }
47 |
48 | // STOP OMIT
49 |
50 | m := f.(map[string]interface{})
51 |
52 | for k, v := range m {
53 | switch vv := v.(type) {
54 | case string:
55 | fmt.Println(k, "is string", vv)
56 | case int:
57 | fmt.Println(k, "is int", vv)
58 | case []interface{}:
59 | fmt.Println(k, "is an array:")
60 | for i, u := range vv {
61 | fmt.Println(i, u)
62 | }
63 | default:
64 | fmt.Println(k, "is of a type I don't know how to handle")
65 | }
66 | }
67 |
68 | // STOP OMIT
69 | }
70 |
71 | func main() {
72 | Decode()
73 | }
74 |
--------------------------------------------------------------------------------
/_content/doc/progs/json4.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "encoding/json"
9 | "log"
10 | "reflect"
11 | )
12 |
13 | type FamilyMember struct {
14 | Name string
15 | Age int
16 | Parents []string
17 | }
18 |
19 | // STOP OMIT
20 |
21 | func Decode() {
22 | b := []byte(`{"Name":"Bob","Age":20,"Parents":["Morticia", "Gomez"]}`)
23 | var m FamilyMember
24 | err := json.Unmarshal(b, &m)
25 |
26 | // STOP OMIT
27 |
28 | if err != nil {
29 | panic(err)
30 | }
31 |
32 | expected := FamilyMember{
33 | Name: "Bob",
34 | Age: 20,
35 | Parents: []string{"Morticia", "Gomez"},
36 | }
37 |
38 | if !reflect.DeepEqual(expected, m) {
39 | log.Panicf("Error unmarshaling %q, expected %q, got %q", b, expected, m)
40 | }
41 | }
42 |
43 | func main() {
44 | Decode()
45 | }
46 |
--------------------------------------------------------------------------------
/_content/doc/progs/json5.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "encoding/json"
9 | "log"
10 | "os"
11 | )
12 |
13 | func main() {
14 | dec := json.NewDecoder(os.Stdin)
15 | enc := json.NewEncoder(os.Stdout)
16 | for {
17 | var v map[string]interface{}
18 | if err := dec.Decode(&v); err != nil {
19 | log.Println(err)
20 | return
21 | }
22 | for k := range v {
23 | if k != "Name" {
24 | delete(v, k)
25 | }
26 | }
27 | if err := enc.Encode(&v); err != nil {
28 | log.Println(err)
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/_content/doc/progs/slices.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "io/ioutil"
9 | "regexp"
10 | )
11 |
12 | func AppendByte(slice []byte, data ...byte) []byte {
13 | m := len(slice)
14 | n := m + len(data)
15 | if n > cap(slice) { // if necessary, reallocate
16 | // allocate double what's needed, for future growth.
17 | newSlice := make([]byte, (n+1)*2)
18 | copy(newSlice, slice)
19 | slice = newSlice
20 | }
21 | slice = slice[0:n]
22 | copy(slice[m:n], data)
23 | return slice
24 | }
25 |
26 | // STOP OMIT
27 |
28 | // Filter returns a new slice holding only
29 | // the elements of s that satisfy fn.
30 | func Filter(s []int, fn func(int) bool) []int {
31 | var p []int // == nil
32 | for _, i := range s {
33 | if fn(i) {
34 | p = append(p, i)
35 | }
36 | }
37 | return p
38 | }
39 |
40 | // STOP OMIT
41 |
42 | var digitRegexp = regexp.MustCompile("[0-9]+")
43 |
44 | func FindDigits(filename string) []byte {
45 | b, _ := ioutil.ReadFile(filename)
46 | return digitRegexp.Find(b)
47 | }
48 |
49 | // STOP OMIT
50 |
51 | func CopyDigits(filename string) []byte {
52 | b, _ := ioutil.ReadFile(filename)
53 | b = digitRegexp.Find(b)
54 | c := make([]byte, len(b))
55 | copy(c, b)
56 | return c
57 | }
58 |
59 | // STOP OMIT
60 |
61 | func main() {
62 | // place holder; no need to run
63 | }
64 |
--------------------------------------------------------------------------------
/_content/doc/progs/timeout1.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package timeout
6 |
7 | import (
8 | "time"
9 | )
10 |
11 | func Timeout() {
12 | ch := make(chan bool, 1)
13 | timeout := make(chan bool, 1)
14 | go func() {
15 | time.Sleep(1 * time.Second)
16 | timeout <- true
17 | }()
18 |
19 | // STOP OMIT
20 |
21 | select {
22 | case <-ch:
23 | // a read from ch has occurred
24 | case <-timeout:
25 | // the read from ch has timed out
26 | }
27 |
28 | // STOP OMIT
29 | }
30 |
--------------------------------------------------------------------------------
/_content/doc/progs/timeout2.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package query
6 |
7 | type Conn string
8 |
9 | func (c Conn) DoQuery(query string) Result {
10 | return Result("result")
11 | }
12 |
13 | type Result string
14 |
15 | func Query(conns []Conn, query string) Result {
16 | ch := make(chan Result, 1)
17 | for _, conn := range conns {
18 | go func(c Conn) {
19 | select {
20 | case ch <- c.DoQuery(query):
21 | default:
22 | }
23 | }(conn)
24 | }
25 | return <-ch
26 | }
27 |
28 | // STOP OMIT
29 |
--------------------------------------------------------------------------------
/_content/doc/share.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/studygolang/website/2438e6b39da44a6c41afca996c9e56695448bada/_content/doc/share.png
--------------------------------------------------------------------------------
/_content/doc/tos.html:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 | The Go website (the "Website") is hosted by Google.
7 | By using and/or visiting the Website, you consent to be bound by Google's general
8 | Terms of Service
9 | and Google's general
10 | Privacy Policy.
11 |
7 | In this tutorial, you wrote functions that you packaged into two modules: one
8 | with logic for sending greetings; the other as a consumer for the first.
9 |
43 | {{end}} 44 | {{.XML}} 45 |