code.html 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. <!--{
  2. "Title": "How to Write Go Code"
  3. }-->
  4. <h2 id="Introduction">Introduction</h2>
  5. <p>
  6. This document demonstrates the development of a simple Go package and
  7. introduces the <a href="/cmd/go/">go tool</a>, the standard way to fetch,
  8. build, and install Go packages and commands.
  9. </p>
  10. <p>
  11. The <code>go</code> tool requires you to organize your code in a specific
  12. way. Please read this document carefully.
  13. It explains the simplest way to get up and running with your Go installation.
  14. </p>
  15. <p>
  16. A similar explanation is available as a
  17. <a href="//www.youtube.com/watch?v=XCsL89YtqCs">screencast</a>.
  18. </p>
  19. <h2 id="Organization">Code organization</h2>
  20. <h3 id="Overview">Overview</h3>
  21. <ul>
  22. <li>Go programmers typically keep all their Go code in a single <i>workspace</i>.</li>
  23. <li>A workspace contains many version control <i>repositories</i>
  24. (managed by Git, for example).</li>
  25. <li>Each repository contains one or more <i>packages</i>.</li>
  26. <li>Each package consists of one or more Go source files in a single directory.</li>
  27. <li>The path to a package's directory determines its <i>import path</i>.</li>
  28. </ul>
  29. <p>
  30. Note that this differs from other programming environments in which every
  31. project has a separate workspace and workspaces are closely tied to version
  32. control repositories.
  33. </p>
  34. <h3 id="Workspaces">Workspaces</h3>
  35. <p>
  36. A workspace is a directory hierarchy with two directories at its root:
  37. </p>
  38. <ul>
  39. <li><code>src</code> contains Go source files, and
  40. <li><code>bin</code> contains executable commands.
  41. </ul>
  42. <p>
  43. The <code>go</code> tool builds and installs binaries to the <code>bin</code> directory.
  44. </p>
  45. <p>
  46. The <code>src</code> subdirectory typically contains multiple version control
  47. repositories (such as for Git or Mercurial) that track the development of one
  48. or more source packages.
  49. </p>
  50. <p>
  51. To give you an idea of how a workspace looks in practice, here's an example:
  52. </p>
  53. <pre>
  54. bin/
  55. hello # command executable
  56. outyet # command executable
  57. src/
  58. <a href="https://github.com/golang/example/">github.com/golang/example/</a>
  59. .git/ # Git repository metadata
  60. hello/
  61. hello.go # command source
  62. outyet/
  63. main.go # command source
  64. main_test.go # test source
  65. stringutil/
  66. reverse.go # package source
  67. reverse_test.go # test source
  68. <a href="https://golang.org/x/image/">golang.org/x/image/</a>
  69. .git/ # Git repository metadata
  70. bmp/
  71. reader.go # package source
  72. writer.go # package source
  73. ... (many more repositories and packages omitted) ...
  74. </pre>
  75. <p>
  76. The tree above shows a workspace containing two repositories
  77. (<code>example</code> and <code>image</code>).
  78. The <code>example</code> repository contains two commands (<code>hello</code>
  79. and <code>outyet</code>) and one library (<code>stringutil</code>).
  80. The <code>image</code> repository contains the <code>bmp</code> package
  81. and <a href="https://godoc.org/golang.org/x/image">several others</a>.
  82. </p>
  83. <p>
  84. A typical workspace contains many source repositories containing many
  85. packages and commands. Most Go programmers keep <i>all</i> their Go source code
  86. and dependencies in a single workspace.
  87. </p>
  88. <p>
  89. Note that symbolic links should <b>not</b> be used to link files or directories into your workspace.
  90. </p>
  91. <p>
  92. Commands and libraries are built from different kinds of source packages.
  93. We will discuss the distinction <a href="#PackageNames">later</a>.
  94. </p>
  95. <h3 id="GOPATH">The <code>GOPATH</code> environment variable</h3>
  96. <p>
  97. The <code>GOPATH</code> environment variable specifies the location of your
  98. workspace. It defaults to a directory named <code>go</code> inside your home directory,
  99. so <code>$HOME/go</code> on Unix,
  100. <code>$home/go</code> on Plan 9,
  101. and <code>%USERPROFILE%\go</code> (usually <code>C:\Users\YourName\go</code>) on Windows.
  102. </p>
  103. <p>
  104. If you would like to work in a different location, you will need to
  105. <a href="https://golang.org/wiki/SettingGOPATH">set <code>GOPATH</code></a>
  106. to the path to that directory.
  107. (Another common setup is to set <code>GOPATH=$HOME</code>.)
  108. Note that <code>GOPATH</code> must <b>not</b> be the
  109. same path as your Go installation.
  110. </p>
  111. <p>
  112. The command <code>go</code> <code>env</code> <code>GOPATH</code>
  113. prints the effective current <code>GOPATH</code>;
  114. it prints the default location if the environment variable is unset.
  115. </p>
  116. <p>
  117. For convenience, add the workspace's <code>bin</code> subdirectory
  118. to your <code>PATH</code>:
  119. </p>
  120. <pre>
  121. $ <b>export PATH=$PATH:$(go env GOPATH)/bin</b>
  122. </pre>
  123. <p>
  124. The scripts in the rest of this document use <code>$GOPATH</code>
  125. instead of <code>$(go env GOPATH)</code> for brevity.
  126. To make the scripts run as written
  127. if you have not set GOPATH,
  128. you can substitute $HOME/go in those commands
  129. or else run:
  130. </p>
  131. <pre>
  132. $ <b>export GOPATH=$(go env GOPATH)</b>
  133. </pre>
  134. <p>
  135. To learn more about the <code>GOPATH</code> environment variable, see
  136. <a href="/cmd/go/#hdr-GOPATH_environment_variable"><code>'go help gopath'</code></a>.
  137. </p>
  138. <p>
  139. To use a custom workspace location,
  140. <a href="https://golang.org/wiki/SettingGOPATH">set the <code>GOPATH</code> environment variable</a>.
  141. </p>
  142. <h3 id="ImportPaths">Import paths</h3>
  143. <p>
  144. An <i>import path</i> is a string that uniquely identifies a package.
  145. A package's import path corresponds to its location inside a workspace
  146. or in a remote repository (explained below).
  147. </p>
  148. <p>
  149. The packages from the standard library are given short import paths such as
  150. <code>"fmt"</code> and <code>"net/http"</code>.
  151. For your own packages, you must choose a base path that is unlikely to
  152. collide with future additions to the standard library or other external
  153. libraries.
  154. </p>
  155. <p>
  156. If you keep your code in a source repository somewhere, then you should use the
  157. root of that source repository as your base path.
  158. For instance, if you have a <a href="https://github.com/">GitHub</a> account at
  159. <code>github.com/user</code>, that should be your base path.
  160. </p>
  161. <p>
  162. Note that you don't need to publish your code to a remote repository before you
  163. can build it. It's just a good habit to organize your code as if you will
  164. publish it someday. In practice you can choose any arbitrary path name,
  165. as long as it is unique to the standard library and greater Go ecosystem.
  166. </p>
  167. <p>
  168. We'll use <code>github.com/user</code> as our base path. Create a directory
  169. inside your workspace in which to keep source code:
  170. </p>
  171. <pre>
  172. $ <b>mkdir -p $GOPATH/src/github.com/user</b>
  173. </pre>
  174. <h3 id="Command">Your first program</h3>
  175. <p>
  176. To compile and run a simple program, first choose a package path (we'll use
  177. <code>github.com/user/hello</code>) and create a corresponding package directory
  178. inside your workspace:
  179. </p>
  180. <pre>
  181. $ <b>mkdir $GOPATH/src/github.com/user/hello</b>
  182. </pre>
  183. <p>
  184. Next, create a file named <code>hello.go</code> inside that directory,
  185. containing the following Go code.
  186. </p>
  187. <pre>
  188. package main
  189. import "fmt"
  190. func main() {
  191. fmt.Println("Hello, world.")
  192. }
  193. </pre>
  194. <p>
  195. Now you can build and install that program with the <code>go</code> tool:
  196. </p>
  197. <pre>
  198. $ <b>go install github.com/user/hello</b>
  199. </pre>
  200. <p>
  201. Note that you can run this command from anywhere on your system. The
  202. <code>go</code> tool finds the source code by looking for the
  203. <code>github.com/user/hello</code> package inside the workspace specified by
  204. <code>GOPATH</code>.
  205. </p>
  206. <p>
  207. You can also omit the package path if you run <code>go install</code> from the
  208. package directory:
  209. </p>
  210. <pre>
  211. $ <b>cd $GOPATH/src/github.com/user/hello</b>
  212. $ <b>go install</b>
  213. </pre>
  214. <p>
  215. This command builds the <code>hello</code> command, producing an executable
  216. binary. It then installs that binary to the workspace's <code>bin</code>
  217. directory as <code>hello</code> (or, under Windows, <code>hello.exe</code>).
  218. In our example, that will be <code>$GOPATH/bin/hello</code>, which is
  219. <code>$HOME/go/bin/hello</code>.
  220. </p>
  221. <p>
  222. The <code>go</code> tool will only print output when an error occurs, so if
  223. these commands produce no output they have executed successfully.
  224. </p>
  225. <p>
  226. You can now run the program by typing its full path at the command line:
  227. </p>
  228. <pre>
  229. $ <b>$GOPATH/bin/hello</b>
  230. Hello, world.
  231. </pre>
  232. <p>
  233. Or, as you have added <code>$GOPATH/bin</code> to your <code>PATH</code>,
  234. just type the binary name:
  235. </p>
  236. <pre>
  237. $ <b>hello</b>
  238. Hello, world.
  239. </pre>
  240. <p>
  241. If you're using a source control system, now would be a good time to initialize
  242. a repository, add the files, and commit your first change. Again, this step is
  243. optional: you do not need to use source control to write Go code.
  244. </p>
  245. <pre>
  246. $ <b>cd $GOPATH/src/github.com/user/hello</b>
  247. $ <b>git init</b>
  248. Initialized empty Git repository in /home/user/work/src/github.com/user/hello/.git/
  249. $ <b>git add hello.go</b>
  250. $ <b>git commit -m "initial commit"</b>
  251. [master (root-commit) 0b4507d] initial commit
  252. 1 file changed, 1 insertion(+)
  253. create mode 100644 hello.go
  254. </pre>
  255. <p>
  256. Pushing the code to a remote repository is left as an exercise for the reader.
  257. </p>
  258. <h3 id="Library">Your first library</h3>
  259. <p>
  260. Let's write a library and use it from the <code>hello</code> program.
  261. </p>
  262. <p>
  263. Again, the first step is to choose a package path (we'll use
  264. <code>github.com/user/stringutil</code>) and create the package directory:
  265. </p>
  266. <pre>
  267. $ <b>mkdir $GOPATH/src/github.com/user/stringutil</b>
  268. </pre>
  269. <p>
  270. Next, create a file named <code>reverse.go</code> in that directory with the
  271. following contents.
  272. </p>
  273. <pre>
  274. // Package stringutil contains utility functions for working with strings.
  275. package stringutil
  276. // Reverse returns its argument string reversed rune-wise left to right.
  277. func Reverse(s string) string {
  278. r := []rune(s)
  279. for i, j := 0, len(r)-1; i &lt; len(r)/2; i, j = i+1, j-1 {
  280. r[i], r[j] = r[j], r[i]
  281. }
  282. return string(r)
  283. }
  284. </pre>
  285. <p>
  286. Now, test that the package compiles with <code>go build</code>:
  287. </p>
  288. <pre>
  289. $ <b>go build github.com/user/stringutil</b>
  290. </pre>
  291. <p>
  292. Or, if you are working in the package's source directory, just:
  293. </p>
  294. <pre>
  295. $ <b>go build</b>
  296. </pre>
  297. <p>
  298. This won't produce an output file.
  299. Instead it saves the compiled package in the local build cache.
  300. </p>
  301. <p>
  302. After confirming that the <code>stringutil</code> package builds,
  303. modify your original <code>hello.go</code> (which is in
  304. <code>$GOPATH/src/github.com/user/hello</code>) to use it:
  305. </p>
  306. <pre>
  307. package main
  308. import (
  309. "fmt"
  310. <b>"github.com/user/stringutil"</b>
  311. )
  312. func main() {
  313. fmt.Println(stringutil.Reverse("!oG ,olleH"))
  314. }
  315. </pre>
  316. <p>
  317. Install the <code>hello</code> program:
  318. </p>
  319. <pre>
  320. $ <b>go install github.com/user/hello</b>
  321. </pre>
  322. <p>
  323. Running the new version of the program, you should see a new, reversed message:
  324. </p>
  325. <pre>
  326. $ <b>hello</b>
  327. Hello, Go!
  328. </pre>
  329. <p>
  330. After the steps above, your workspace should look like this:
  331. </p>
  332. <pre>
  333. bin/
  334. hello # command executable
  335. src/
  336. github.com/user/
  337. hello/
  338. hello.go # command source
  339. stringutil/
  340. reverse.go # package source
  341. </pre>
  342. <h3 id="PackageNames">Package names</h3>
  343. <p>
  344. The first statement in a Go source file must be
  345. </p>
  346. <pre>
  347. package <i>name</i>
  348. </pre>
  349. <p>
  350. where <code><i>name</i></code> is the package's default name for imports.
  351. (All files in a package must use the same <code><i>name</i></code>.)
  352. </p>
  353. <p>
  354. Go's convention is that the package name is the last element of the
  355. import path: the package imported as "<code>crypto/rot13</code>"
  356. should be named <code>rot13</code>.
  357. </p>
  358. <p>
  359. Executable commands must always use <code>package main</code>.
  360. </p>
  361. <p>
  362. There is no requirement that package names be unique
  363. across all packages linked into a single binary,
  364. only that the import paths (their full file names) be unique.
  365. </p>
  366. <p>
  367. See <a href="/doc/effective_go.html#names">Effective Go</a> to learn more about
  368. Go's naming conventions.
  369. </p>
  370. <h2 id="Testing">Testing</h2>
  371. <p>
  372. Go has a lightweight test framework composed of the <code>go test</code>
  373. command and the <code>testing</code> package.
  374. </p>
  375. <p>
  376. You write a test by creating a file with a name ending in <code>_test.go</code>
  377. that contains functions named <code>TestXXX</code> with signature
  378. <code>func (t *testing.T)</code>.
  379. The test framework runs each such function;
  380. if the function calls a failure function such as <code>t.Error</code> or
  381. <code>t.Fail</code>, the test is considered to have failed.
  382. </p>
  383. <p>
  384. Add a test to the <code>stringutil</code> package by creating the file
  385. <code>$GOPATH/src/github.com/user/stringutil/reverse_test.go</code> containing
  386. the following Go code.
  387. </p>
  388. <pre>
  389. package stringutil
  390. import "testing"
  391. func TestReverse(t *testing.T) {
  392. cases := []struct {
  393. in, want string
  394. }{
  395. {"Hello, world", "dlrow ,olleH"},
  396. {"Hello, 世界", "界世 ,olleH"},
  397. {"", ""},
  398. }
  399. for _, c := range cases {
  400. got := Reverse(c.in)
  401. if got != c.want {
  402. t.Errorf("Reverse(%q) == %q, want %q", c.in, got, c.want)
  403. }
  404. }
  405. }
  406. </pre>
  407. <p>
  408. Then run the test with <code>go test</code>:
  409. </p>
  410. <pre>
  411. $ <b>go test github.com/user/stringutil</b>
  412. ok github.com/user/stringutil 0.165s
  413. </pre>
  414. <p>
  415. As always, if you are running the <code>go</code> tool from the package
  416. directory, you can omit the package path:
  417. </p>
  418. <pre>
  419. $ <b>go test</b>
  420. ok github.com/user/stringutil 0.165s
  421. </pre>
  422. <p>
  423. Run <code><a href="/cmd/go/#hdr-Test_packages">go help test</a></code> and see the
  424. <a href="/pkg/testing/">testing package documentation</a> for more detail.
  425. </p>
  426. <h2 id="remote">Remote packages</h2>
  427. <p>
  428. An import path can describe how to obtain the package source code using a
  429. revision control system such as Git or Mercurial. The <code>go</code> tool uses
  430. this property to automatically fetch packages from remote repositories.
  431. For instance, the examples described in this document are also kept in a
  432. Git repository hosted at GitHub
  433. <code><a href="https://github.com/golang/example">github.com/golang/example</a></code>.
  434. If you include the repository URL in the package's import path,
  435. <code>go get</code> will fetch, build, and install it automatically:
  436. </p>
  437. <pre>
  438. $ <b>go get github.com/golang/example/hello</b>
  439. $ <b>$GOPATH/bin/hello</b>
  440. Hello, Go examples!
  441. </pre>
  442. <p>
  443. If the specified package is not present in a workspace, <code>go get</code>
  444. will place it inside the first workspace specified by <code>GOPATH</code>.
  445. (If the package does already exist, <code>go get</code> skips the remote
  446. fetch and behaves the same as <code>go install</code>.)
  447. </p>
  448. <p>
  449. After issuing the above <code>go get</code> command, the workspace directory
  450. tree should now look like this:
  451. </p>
  452. <pre>
  453. bin/
  454. hello # command executable
  455. src/
  456. github.com/golang/example/
  457. .git/ # Git repository metadata
  458. hello/
  459. hello.go # command source
  460. stringutil/
  461. reverse.go # package source
  462. reverse_test.go # test source
  463. github.com/user/
  464. hello/
  465. hello.go # command source
  466. stringutil/
  467. reverse.go # package source
  468. reverse_test.go # test source
  469. </pre>
  470. <p>
  471. The <code>hello</code> command hosted at GitHub depends on the
  472. <code>stringutil</code> package within the same repository. The imports in
  473. <code>hello.go</code> file use the same import path convention, so the
  474. <code>go get</code> command is able to locate and install the dependent
  475. package, too.
  476. </p>
  477. <pre>
  478. import "github.com/golang/example/stringutil"
  479. </pre>
  480. <p>
  481. This convention is the easiest way to make your Go packages available for
  482. others to use.
  483. The <a href="//golang.org/wiki/Projects">Go Wiki</a>
  484. and <a href="//godoc.org/">godoc.org</a>
  485. provide lists of external Go projects.
  486. </p>
  487. <p>
  488. For more information on using remote repositories with the <code>go</code> tool, see
  489. <code><a href="/cmd/go/#hdr-Remote_import_paths">go help importpath</a></code>.
  490. </p>
  491. <h2 id="next">What's next</h2>
  492. <p>
  493. Subscribe to the
  494. <a href="//groups.google.com/group/golang-announce">golang-announce</a>
  495. mailing list to be notified when a new stable version of Go is released.
  496. </p>
  497. <p>
  498. See <a href="/doc/effective_go.html">Effective Go</a> for tips on writing
  499. clear, idiomatic Go code.
  500. </p>
  501. <p>
  502. Take <a href="//tour.golang.org/">A Tour of Go</a> to learn the language
  503. proper.
  504. </p>
  505. <p>
  506. Visit the <a href="/doc/#articles">documentation page</a> for a set of in-depth
  507. articles about the Go language and its libraries and tools.
  508. </p>
  509. <h2 id="help">Getting help</h2>
  510. <p>
  511. For real-time help, ask the helpful gophers in <code>#go-nuts</code> on the
  512. <a href="https://freenode.net/">Freenode</a> IRC server.
  513. </p>
  514. <p>
  515. The official mailing list for discussion of the Go language is
  516. <a href="//groups.google.com/group/golang-nuts">Go Nuts</a>.
  517. </p>
  518. <p>
  519. Report bugs using the
  520. <a href="//golang.org/issue">Go issue tracker</a>.
  521. </p>