github.com/spotify/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/misc/tour/content/tour.article (about) 1 A Tour of Go 2 3 The Go Authors 4 http://golang.org 5 6 # Throughout this file are a series of lines that begin with 7 # the string "#appengine: ". These lines are included in 8 # the tour content when deployed as an App Engine app. 9 # Furthermore, a single non-blank line that immediately follows 10 # a run of "#appengine: " lines will be hidden. This is so that 11 # App Engine-specific content may replace existing content. 12 # For example, this paragraph 13 # We are running 14 # #appengine: on App Engine. 15 # locally. 16 # Yay! 17 # reads as "We are running on App Engine. Yay!" on App Engine, 18 # and "We are running locally. Yay!" otherwise. 19 20 * Hello, 世界 21 22 Welcome to a tour of the [[http://golang.org/][Go programming language]]. 23 24 The tour is divided into three sections: basic concepts, methods and interfaces, and concurrency. 25 26 Throughout the tour you will find a series of exercises for you to complete. 27 28 The tour is interactive. Click the Run button now (or type Shift-Enter) to compile and run the program on 29 #appengine: a remote server. 30 your computer. 31 The result is displayed below the code. 32 33 These example programs demonstrate different aspects of Go. The programs in the tour are meant to be starting points for your own experimentation. 34 35 Edit the program and run it again. 36 37 When you're ready to move on, click the right arrow down below or type the PageDown key. 38 You can also navigate using the menu under the "Go" flag at the top of the page. 39 40 .play prog/tour/hello.go 41 42 * Go local 43 44 The tour is available in other languages: 45 46 - [[http://go-tour-br.appspot.com/][Brazilian Portuguese — Português do Brasil]] 47 - [[http://go-tour-ca.appspot.com/][Catalan — Català]] 48 - [[http://go-tour-es.appspot.com/][Spanish — Español]] 49 - [[http://go-tour-fr.appspot.com/][French - Français]] 50 - [[http://go-tour-he.appspot.com/][Hebrew — עִבְרִית]] 51 - [[http://go-tour-jp.appspot.com/][Japanese — 日本語]] 52 - [[http://go-tour-kr.appspot.com/][Korean — 한국어]] 53 - [[http://go-tour-ro.appspot.com/][Romanian - Română]] 54 - [[http://tur.golang.org.tr/][Turkish - Türkçe]] 55 - [[http://go-tour-zh.appspot.com/][Chinese — 简体中文]] 56 57 Click the "next" button or type PageDown to continue. 58 59 #appengine: * The Go Playground 60 #appengine: 61 #appengine: This tour is built atop the [[http://play.golang.org/][Go Playground]], a 62 #appengine: web service that runs on [[http://golang.org/][golang.org]]'s servers. 63 #appengine: 64 #appengine: The service receives a Go program, compiles, links, and runs the program inside 65 #appengine: a sandbox, then returns the output. 66 #appengine: 67 #appengine: There are limitations to the programs that can be run in the playground: 68 #appengine: 69 #appengine: - The only communication a playground program has to the outside world is by writing to standard output and standard error. 70 #appengine: - In the playground the time begins at 2009-11-10 23:00:00 UTC (determining the significance of this date is an exercise for the reader). This makes it easier to cache programs by giving them deterministic output. 71 #appengine: - There are also limits on execution time and on CPU and memory usage, and the program is restricted to running in a single thread (but may use many goroutines). 72 #appengine: 73 #appengine: The playground uses the latest stable release of Go. 74 #appengine: 75 #appengine: Read "[[http://blog.golang.org/playground][Inside the Go Playground]]" to learn more. 76 #appengine: 77 #appengine: .play prog/tour/sandbox.go 78 79 * Packages 80 81 Every Go program is made up of packages. 82 83 Programs start running in package `main`. 84 85 This program is using the packages with import paths `"fmt"` and `"math/rand"`. 86 87 By convention, the package name is the same as the last element of the import path. For instance, the `"math/rand"` package comprises files that begin with the statement `package`rand`. 88 89 #appengine: *Note:* the environment in which these programs are executed is 90 #appengine: deterministic, so `rand.Intn` will always return the same number. 91 #appengine: 92 #appengine: (To see a different number, seed the number generator; see [[http://golang.org/pkg/math/rand/#Seed][`rand.Seed`]].) 93 94 .play prog/tour/packages.go 95 96 * Imports 97 98 This code groups the imports into a parenthesized, "factored" import statement. You can also write multiple import statements, like: 99 100 import "fmt" 101 import "math" 102 103 .play prog/tour/imports.go 104 105 * Exported names 106 107 After importing a package, you can refer to the names it exports. 108 109 In Go, a name is exported if it begins with a capital letter. 110 111 `Foo` is an exported name, as is `FOO`. The name `foo` is not exported. 112 113 Run the code. Then rename `math.pi` to `math.Pi` and try it again. 114 115 .play prog/tour/exported-names.go 116 117 * Functions 118 119 A function can take zero or more arguments. 120 121 In this example, `add` takes two parameters of type `int`. 122 123 Notice that the type comes _after_ the variable name. 124 125 (For more about why types look the way they do, see the [[http://golang.org/doc/articles/gos_declaration_syntax.html][article on Go's declaration syntax]].) 126 127 .play prog/tour/functions.go 128 129 * Functions continued 130 131 When two or more consecutive named function parameters share a type, you can omit the type from all but the last. 132 133 In this example, we shortened 134 135 x int, y int 136 137 to 138 139 x, y int 140 141 .play prog/tour/functions-continued.go 142 143 * Multiple results 144 145 A function can return any number of results. 146 147 This function returns two strings. 148 149 .play prog/tour/multiple-results.go 150 151 * Named results 152 153 Functions take parameters. In Go, functions can return multiple "result parameters", not just a single value. They can be named and act just like variables. 154 155 If the result parameters are named, a `return` statement without arguments returns the current values of the results. 156 157 .play prog/tour/named-results.go 158 159 * Variables 160 161 The `var` statement declares a list of variables; as in function argument lists, the type is last. 162 163 .play prog/tour/variables.go 164 165 * Variables with initializers 166 167 A var declaration can include initializers, one per variable. 168 169 If an initializer is present, the type can be omitted; the variable will take the type of the initializer. 170 171 .play prog/tour/variables-with-initializers.go 172 173 * Short variable declarations 174 175 Inside a function, the `:=` short assignment statement can be used in place of a `var` declaration with implicit type. 176 177 Outside a function, every construct begins with a keyword (`var`, `func`, and so on) and the `:=` construct is not available. 178 179 .play prog/tour/short-variable-declarations.go 180 181 * Basic types 182 183 Go's basic types are 184 185 bool 186 187 string 188 189 int int8 int16 int32 int64 190 uint uint8 uint16 uint32 uint64 uintptr 191 192 byte // alias for uint8 193 194 rune // alias for int32 195 // represents a Unicode code point 196 197 float32 float64 198 199 complex64 complex128 200 201 .play prog/tour/basic-types.go 202 203 * Type conversions 204 205 The expression `T(v)` converts the value `v` to the type `T`. 206 207 Some numeric conversions: 208 209 var i int = 42 210 var f float64 = float64(i) 211 var u uint = uint(f) 212 213 Or, put more simply: 214 215 i := 42 216 f := float64(i) 217 u := uint(f) 218 219 Unlike in C, in Go assignment between items of different type requires an 220 explicit conversion. 221 Try removing the `float64` or `int` conversions in the example and see what happens. 222 223 .play prog/tour/type-conversions.go 224 225 * Constants 226 227 Constants are declared like variables, but with the `const` keyword. 228 229 Constants can be character, string, boolean, or numeric values. 230 231 Constants cannot be declared using the `:=` syntax. 232 233 .play prog/tour/constants.go 234 235 * Numeric Constants 236 237 Numeric constants are high-precision _values_. 238 239 An untyped constant takes the type needed by its context. 240 241 Try printing `needInt(Big)` too. 242 243 .play prog/tour/numeric-constants.go 244 245 * For 246 247 Go has only one looping construct, the `for` loop. 248 249 The basic `for` loop looks as it does in C or Java, except that the `(`)` are gone (they are not even optional) and the `{`}` are required. 250 251 .play prog/tour/for.go 252 253 * For continued 254 255 As in C or Java, you can leave the pre and post statements empty. 256 257 .play prog/tour/for-continued.go 258 259 * For is Go's "while" 260 261 At that point you can drop the semicolons: C's `while` is spelled `for` in Go. 262 263 .play prog/tour/for-is-gos-while.go 264 265 * Forever 266 267 If you omit the loop condition it loops forever, so an infinite loop is compactly expressed. 268 269 .play prog/tour/forever.go 270 271 * If 272 273 The `if` statement looks as it does in C or Java, except that the `(`)` are gone and the `{`}` are required. 274 275 (Sound familiar?) 276 277 .play prog/tour/if.go 278 279 * If with a short statement 280 281 Like `for`, the `if` statement can start with a short statement to execute before the condition. 282 283 Variables declared by the statement are only in scope until the end of the `if`. 284 285 (Try using `v` in the last `return` statement.) 286 287 .play prog/tour/if-with-a-short-statement.go 288 289 * If and else 290 291 Variables declared inside an `if` short statement are also available inside any of the `else` blocks. 292 293 .play prog/tour/if-and-else.go 294 295 * Exercise: Loops and Functions 296 297 As a simple way to play with functions and loops, implement the square root function using Newton's method. 298 299 In this case, Newton's method is to approximate `Sqrt(x)` by picking a starting point _z_ and then repeating: 300 301 .image static/newton.png 302 303 To begin with, just repeat that calculation 10 times and see how close you get to the answer for various values (1, 2, 3, ...). 304 305 Next, change the loop condition to stop once the value has stopped changing (or only changes by a very small delta). See if that's more or fewer iterations. How close are you to the [[http://golang.org/pkg/math/#Sqrt][math.Sqrt]]? 306 307 Hint: to declare and initialize a floating point value, give it floating point syntax or use a conversion: 308 309 z := float64(1) 310 z := 1.0 311 312 .play prog/tour/exercise-loops-and-functions.go 313 314 * Structs 315 316 A `struct` is a collection of fields. 317 318 (And a `type` declaration does what you'd expect.) 319 320 .play prog/tour/structs.go 321 322 * Struct Fields 323 324 Struct fields are accessed using a dot. 325 326 .play prog/tour/struct-fields.go 327 328 * Pointers 329 330 Go has pointers, but no pointer arithmetic. 331 332 Struct fields can be accessed through a struct pointer. The indirection through the pointer is transparent. 333 334 .play prog/tour/pointers.go 335 336 * Struct Literals 337 338 A struct literal denotes a newly allocated struct value by listing the values of its fields. 339 340 You can list just a subset of fields by using the `Name:` syntax. (And the order of named fields is irrelevant.) 341 342 The special prefix `&` constructs a pointer to a newly allocated struct. 343 344 .play prog/tour/struct-literals.go 345 346 * The new function 347 348 The expression `new(T)` allocates a zeroed `T` value and returns a pointer to it. 349 350 var t *T = new(T) 351 352 or 353 354 t := new(T) 355 356 .play prog/tour/the-new-function.go 357 358 * Arrays 359 360 The type `[n]T` is an array of `n` values of type `T`. 361 362 The expression 363 364 var a [10]int 365 366 declares a variable `a` as an array of ten integers. 367 368 An array's length is part of its type, so arrays cannot be resized. 369 This seems limiting, but don't worry; 370 Go provides a convenient way of working with arrays. 371 372 .play prog/tour/array.go 373 374 * Slices 375 376 A slice points to an array of values and also includes a length. 377 378 `[]T` is a slice with elements of type `T`. 379 380 .play prog/tour/slices.go 381 382 * Slicing slices 383 384 Slices can be re-sliced, creating a new slice value that points to the same array. 385 386 The expression 387 388 s[lo:hi] 389 390 evaluates to a slice of the elements from `lo` through `hi-1`, inclusive. Thus 391 392 s[lo:lo] 393 394 is empty and 395 396 s[lo:lo+1] 397 398 has one element. 399 400 .play prog/tour/slicing-slices.go 401 402 * Making slices 403 404 Slices are created with the `make` function. It works by allocating a zeroed array and returning a slice that refers to that array: 405 406 a := make([]int, 5) // len(a)=5 407 408 To specify a capacity, pass a third argument to `make`: 409 410 b := make([]int, 0, 5) // len(b)=0, cap(b)=5 411 412 b = b[:cap(b)] // len(b)=5, cap(b)=5 413 b = b[1:] // len(b)=4, cap(b)=4 414 415 .play prog/tour/making-slices.go 416 417 * Nil slices 418 419 The zero value of a slice is `nil`. 420 421 A nil slice has a length and capacity of 0. 422 423 (To learn more about slices, read the [[http://golang.org/doc/articles/slices_usage_and_internals.html][Slices: usage and internals]] article.) 424 425 .play prog/tour/nil-slices.go 426 427 * Range 428 429 The `range` form of the `for` loop iterates over a slice or map. 430 431 .play prog/tour/range.go 432 433 * Range continued 434 435 You can skip the index or value by assigning to `_`. 436 437 If you only want the index, drop the ", value" entirely. 438 439 .play prog/tour/range-continued.go 440 441 * Exercise: Slices 442 443 Implement `Pic`. It should return a slice of length `dy`, each element of which is a slice of `dx` 8-bit unsigned integers. When you run the program, it will display your picture, interpreting the integers as grayscale (well, bluescale) values. 444 445 The choice of image is up to you. Interesting functions include `x^y`, `(x+y)/2`, and `x*y`. 446 447 (You need to use a loop to allocate each `[]uint8` inside the `[][]uint8`.) 448 449 (Use `uint8(intValue)` to convert between types.) 450 451 .play prog/tour/exercise-slices.go 452 453 * Maps 454 455 A map maps keys to values. 456 457 Maps must be created with `make` (not `new`) before use; the `nil` map is empty and cannot be assigned to. 458 459 .play prog/tour/maps.go 460 461 * Map literals 462 463 Map literals are like struct literals, but the keys are required. 464 465 .play prog/tour/map-literals.go 466 467 * Map literals continued 468 469 If the top-level type is just a type name, you can omit it from the elements of the literal. 470 471 .play prog/tour/map-literals-continued.go 472 473 * Mutating Maps 474 475 Insert or update an element in map `m`: 476 477 m[key] = elem 478 479 Retrieve an element: 480 481 elem = m[key] 482 483 Delete an element: 484 485 delete(m, key) 486 487 Test that a key is present with a two-value assignment: 488 489 elem, ok = m[key] 490 491 If `key` is in `m`, `ok` is `true`. If not, `ok` is `false` and `elem` is the zero value for the map's element type. 492 493 Similarly, when reading from a map if the key is not present the result is the zero value for the map's element type. 494 495 .play prog/tour/mutating-maps.go 496 497 * Exercise: Maps 498 499 Implement `WordCount`. It should return a map of the counts of each “word” in the string `s`. The `wc.Test` function runs a test suite against the provided function and prints success or failure. 500 501 You might find [[http://golang.org/pkg/strings/#Fields][strings.Fields]] helpful. 502 503 .play prog/tour/exercise-maps.go 504 505 * Function values 506 507 Functions are values too. 508 509 .play prog/tour/function-values.go 510 511 * Function closures 512 513 Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables. 514 515 For example, the `adder` function returns a closure. Each closure is bound to its own `sum` variable. 516 517 .play prog/tour/function-closures.go 518 519 * Exercise: Fibonacci closure 520 521 Let's have some fun with functions. 522 523 Implement a `fibonacci` function that returns a function (a closure) that returns successive fibonacci numbers. 524 525 .play prog/tour/exercise-fibonacci-closure.go 526 527 * Switch 528 529 You probably knew what `switch` was going to look like. 530 531 A case body breaks automatically, unless it ends with a `fallthrough` statement. 532 533 .play prog/tour/switch.go 534 535 * Switch evaluation order 536 537 Switch cases evaluate cases from top to bottom, stopping when a case succeeds. 538 539 (For example, 540 541 switch i { 542 case 0: 543 case f(): 544 } 545 546 does not call `f` if `i==0`.) 547 548 #appengine: *Note:* Time in the Go playground always appears to start at 549 #appengine: 2009-11-10 23:00:00 UTC, a value whose significance is left as an 550 #appengine: exercise for the reader. 551 552 .play prog/tour/switch-evaluation-order.go 553 554 * Switch with no condition 555 556 Switch without a condition is the same as `switch`true`. 557 558 This construct can be a clean way to write long if-then-else chains. 559 560 .play prog/tour/switch-with-no-condition.go 561 562 * Advanced Exercise: Complex cube roots 563 564 Let's explore Go's built-in support for complex numbers via the `complex64` and `complex128` types. For cube roots, Newton's method amounts to repeating: 565 566 .image static/newton3.png 567 568 Find the cube root of 2, just to make sure the algorithm works. There is a [[http://golang.org/pkg/math/cmplx/#Pow][Pow]] function in the `math/cmplx` package. 569 570 .play prog/tour/advanced-exercise-complex-cube-roots.go 571 572 * Methods and Interfaces 573 574 The next group of slides covers methods and interfaces, the constructs that 575 define objects and their behavior. 576 577 * Methods 578 579 Go does not have classes. However, you can define methods on struct types. 580 581 The _method_receiver_ appears in its own argument list between the `func` keyword and the method name. 582 583 .play prog/tour/methods.go 584 585 * Methods continued 586 587 In fact, you can define a method on _any_ type you define in your package, not just structs. 588 589 You cannot define a method on a type from another package, or on a basic type. 590 591 .play prog/tour/methods-continued.go 592 593 * Methods with pointer receivers 594 595 Methods can be associated with a named type or a pointer to a named type. 596 597 We just saw two `Abs` methods. One on the `*Vertex` pointer type and the other on the `MyFloat` value type. 598 599 There are two reasons to use a pointer receiver. First, to avoid copying the value on each method call (more efficient if the value type is a large struct). Second, so that the method can modify the value that its receiver points to. 600 601 Try changing the declarations of the `Abs` and `Scale` methods to use `Vertex` as the receiver, instead of `*Vertex`. 602 603 The `Scale` method has no effect when `v` is a `Vertex`. `Scale` mutates `v`. When `v` is a value (non-pointer) type, the method sees a copy of the `Vertex` and cannot mutate the original value. 604 605 `Abs` works either way. It only reads `v`. It doesn't matter whether it is reading the original value (through a pointer) or a copy of that value. 606 607 .play prog/tour/methods-with-pointer-receivers.go 608 609 * Interfaces 610 611 An interface type is defined by a set of methods. 612 613 A value of interface type can hold any value that implements those methods. 614 615 *Note:* The code on the left fails to compile. 616 617 `Vertex` doesn't satisfy `Abser` because 618 the `Abs` method is defined only on `*Vertex`, not `Vertex`. 619 620 .play prog/tour/interfaces.go 621 622 * Interfaces are satisfied implicitly 623 624 A type implements an interface by implementing the methods. 625 626 _There_is_no_explicit_declaration_of_intent._ 627 628 Implicit interfaces decouple implementation packages from the packages that define the interfaces: neither depends on the other. 629 630 It also encourages the definition of precise interfaces, because you don't have to find every implementation and tag it with the new interface name. 631 632 [[http://golang.org/pkg/io/][Package io]] defines `Reader` and `Writer`; you don't have to. 633 634 .play prog/tour/interfaces-are-satisfied-implicitly.go 635 636 * Errors 637 638 An error is anything that can describe itself as an error string. The idea is captured by the predefined, built-in interface type, `error`, with its single method, `Error`, returning a string: 639 640 type error interface { 641 Error() string 642 } 643 644 The `fmt` package's various print routines automatically know to call the method when asked to print an `error`. 645 646 .play prog/tour/errors.go 647 648 * Exercise: Errors 649 650 Copy your `Sqrt` function from the earlier exercises and modify it to return an `error` value. 651 652 `Sqrt` should return a non-nil error value when given a negative number, as it doesn't support complex numbers. 653 654 Create a new type 655 656 type ErrNegativeSqrt float64 657 658 and make it an `error` by giving it a 659 660 func (e ErrNegativeSqrt) Error() string 661 662 method such that `ErrNegativeSqrt(-2).Error()` returns `"cannot`Sqrt`negative`number:`-2"`. 663 664 *Note:* a call to `fmt.Print(e)` inside the `Error` method will send the program into an infinite loop. You can avoid this by converting `e` first: `fmt.Print(float64(e))`. Why? 665 666 Change your `Sqrt` function to return an `ErrNegativeSqrt` value when given a negative number. 667 668 .play prog/tour/exercise-errors.go 669 670 * Web servers 671 672 [[http://golang.org/pkg/net/http/][Package http]] serves HTTP requests using any value that implements `http.Handler`: 673 674 package http 675 676 type Handler interface { 677 ServeHTTP(w ResponseWriter, r *Request) 678 } 679 680 In this example, the type `Hello` implements `http.Handler`. 681 682 Visit [[http://localhost:4000/][http://localhost:4000/]] to see the greeting. 683 684 #appengine: *Note:* This example won't run through the web-based tour user 685 #appengine: interface. To try writing web servers you may want to 686 #appengine: [[http://golang.org/doc/install/][Install Go]]. 687 688 .play prog/tour/web-servers.go 689 690 * Exercise: HTTP Handlers 691 692 Implement the following types and define ServeHTTP methods on them. Register them to handle specific paths in your web server. 693 694 type String string 695 696 type Struct struct { 697 Greeting string 698 Punct string 699 Who string 700 } 701 702 For example, you should be able to register handlers using: 703 704 http.Handle("/string", String("I'm a frayed knot.")) 705 http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"}) 706 707 .play prog/tour/exercise-http-handlers.go 708 709 * Images 710 711 [[http://golang.org/pkg/image/#Image][Package image]] defines the `Image` interface: 712 713 package image 714 715 type Image interface { 716 ColorModel() color.Model 717 Bounds() Rectangle 718 At(x, y int) color.Color 719 } 720 721 (See [[http://golang.org/pkg/image/#Image][the documentation]] for all the details.) 722 723 Also, `color.Color` and `color.Model` are interfaces, but we'll ignore that by using the predefined implementations `color.RGBA` and `color.RGBAModel`. These interfaces and types are specified by the [[http://golang.org/pkg/image/color/][image/color package]] 724 725 .play prog/tour/images.go 726 727 * Exercise: Images 728 729 Remember the picture generator you wrote earlier? Let's write another one, but this time it will return an implementation of `image.Image` instead of a slice of data. 730 731 Define your own `Image` type, implement [[http://golang.org/pkg/image/#Image][the necessary methods]], and call `pic.ShowImage`. 732 733 `Bounds` should return a `image.Rectangle`, like `image.Rect(0,`0,`w,`h)`. 734 735 `ColorModel` should return `color.RGBAModel`. 736 737 `At` should return a color; the value `v` in the last picture generator corresponds to `color.RGBA{v,`v,`255,`255}` in this one. 738 739 .play prog/tour/exercise-images.go 740 741 * Exercise: Rot13 Reader 742 743 A common pattern is an [[http://golang.org/pkg/io/#Reader][io.Reader]] that wraps another `io.Reader`, modifying the stream in some way. 744 745 For example, the [[http://golang.org/pkg/compress/gzip/#NewReader][gzip.NewReader]] function takes an `io.Reader` (a stream of gzipped data) and returns a `*gzip.Reader` that also implements `io.Reader` (a stream of the decompressed data). 746 747 Implement a `rot13Reader` that implements `io.Reader` and reads from an `io.Reader`, modifying the stream by applying the [[http://en.wikipedia.org/wiki/ROT13][ROT13]] substitution cipher to all alphabetical characters. 748 749 The `rot13Reader` type is provided for you. Make it an `io.Reader` by implementing its `Read` method. 750 751 .play prog/tour/exercise-rot-reader.go 752 753 * Concurrency 754 755 The next section covers Go's concurrency primitives. 756 757 * Goroutines 758 759 A _goroutine_ is a lightweight thread managed by the Go runtime. 760 761 go f(x, y, z) 762 763 starts a new goroutine running 764 765 f(x, y, z) 766 767 The evaluation of `f`, `x`, `y`, and `z` happens in the current goroutine and the execution of `f` happens in the new goroutine. 768 769 Goroutines run in the same address space, so access to shared memory must be synchronized. The [[http://golang.org/pkg/sync/][`sync`]] package provides useful primitives, although you won't need them much in Go as there are other primitives. (See the next slide.) 770 771 .play prog/tour/goroutines.go 772 773 * Channels 774 775 Channels are a typed conduit through which you can send and receive values with the channel operator, `<-`. 776 777 ch <- v // Send v to channel ch. 778 v := <-ch // Receive from ch, and 779 // assign value to v. 780 781 (The data flows in the direction of the arrow.) 782 783 Like maps and slices, channels must be created before use: 784 785 ch := make(chan int) 786 787 By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables. 788 789 .play prog/tour/channels.go 790 791 * Buffered Channels 792 793 Channels can be _buffered_. Provide the buffer length as the second argument to `make` to initialize a buffered channel: 794 795 ch := make(chan int, 100) 796 797 Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty. 798 799 Modify the example to overfill the buffer and see what happens. 800 801 .play prog/tour/buffered-channels.go 802 803 * Range and Close 804 805 A sender can `close` a channel to indicate that no more values will be sent. Receivers can test whether a channel has been closed by assigning a second parameter to the receive expression: after 806 807 v, ok := <-ch 808 809 `ok` is `false` if there are no more values to receive and the channel is closed. 810 811 The loop `for`i`:=`range`c` receives values from the channel repeatedly until it is closed. 812 813 *Note:* Only the sender should close a channel, never the receiver. Sending on a closed channel will cause a panic. 814 815 *Another*note*: Channels aren't like files; you don't usually need to close them. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a `range` loop. 816 817 .play prog/tour/range-and-close.go 818 819 * Select 820 821 The `select` statement lets a goroutine wait on multiple communication operations. 822 823 A `select` blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready. 824 825 .play prog/tour/select.go 826 827 * Default Selection 828 829 The `default` case in a `select` is run if no other case is ready. 830 831 Use a `default` case to try a send or receive without blocking: 832 833 select { 834 case i := <-c: 835 // use i 836 default: 837 // receiving from c would block 838 } 839 840 .play prog/tour/default-selection.go 841 842 * Exercise: Equivalent Binary Trees 843 844 There can be many different binary trees with the same sequence of values stored at the leaves. For example, here are two binary trees storing the sequence 1, 1, 2, 3, 5, 8, 13. 845 846 .image static/tree.png 847 848 A function to check whether two binary trees store the same sequence is quite complex in most languages. We'll use Go's concurrency and channels to write a simple solution. 849 850 This example uses the `tree` package, which defines the type: 851 852 type Tree struct { 853 Left *Tree 854 Value int 855 Right *Tree 856 } 857 858 * Exercise: Equivalent Binary Trees 859 860 *1.* Implement the `Walk` function. 861 862 *2.* Test the `Walk` function. 863 864 The function `tree.New(k)` constructs a randomly-structured binary tree holding the values `k`, `2k`, `3k`, ..., `10k`. 865 866 Create a new channel `ch` and kick off the walker: 867 868 go Walk(tree.New(1), ch) 869 870 Then read and print 10 values from the channel. It should be the numbers 1, 2, 3, ..., 10. 871 872 *3.* Implement the `Same` function using `Walk` to determine whether `t1` and `t2` store the same values. 873 874 *4.* Test the `Same` function. 875 876 `Same(tree.New(1),`tree.New(1))` should return true, and `Same(tree.New(1),`tree.New(2))` should return false. 877 878 .play prog/tour/exercise-equivalent-binary-trees.go 879 880 * Exercise: Web Crawler 881 882 In this exercise you'll use Go's concurrency features to parallelize a web crawler. 883 884 Modify the `Crawl` function to fetch URLs in parallel without fetching the same URL twice. 885 886 .play prog/tour/exercise-web-crawler.go 887 888 * Where to Go from here... 889 890 #appengine: You can get started by 891 #appengine: [[http://golang.org/doc/install/][installing Go]] or downloading the 892 #appengine: [[http://code.google.com/appengine/downloads.html#Google_App_Engine_SDK_for_Go][Go App Engine SDK]]. 893 894 #appengine: Once you have Go installed, the 895 The 896 [[http://golang.org/doc/][Go Documentation]] is a great place to 897 #appengine: continue. 898 start. 899 It contains references, tutorials, videos, and more. 900 901 To learn how to organize and work with Go code, watch [[http://www.youtube.com/watch?v=XCsL89YtqCs][this screencast]] or read [[http://golang.org/doc/code.html][How to Write Go Code]]. 902 903 If you need help with the standard library, see the [[http://golang.org/pkg/][package reference]]. For help with the language itself, you might be surprised to find the [[http://golang.org/ref/spec][Language Spec]] is quite readable. 904 905 To further explore Go's concurrency model, watch 906 [[http://www.youtube.com/watch?v=f6kdp27TYZs][Go Concurrency Patterns]] 907 ([[http://talks.golang.org/2012/concurrency.slide][slides]]) 908 and 909 [[https://www.youtube.com/watch?v=QDDwwePbDtw][Advanced Go Concurrency Patterns]] 910 ([[http://talks.golang.org/2013/advconc.slide][slides]]) 911 and read the 912 [[http://golang.org/doc/codewalk/sharemem/][Share Memory by Communicating]] 913 codewalk. 914 915 To get started writing web applications, watch 916 [[http://vimeo.com/53221558][A simple programming environment]] 917 ([[http://talks.golang.org/2012/simple.slide][slides]]) 918 and read the 919 [[http://golang.org/doc/articles/wiki/][Writing Web Applications]] tutorial. 920 921 The [[http://golang.org/doc/codewalk/functions/][First Class Functions in Go]] codewalk gives an interesting perspective on Go's function types. 922 923 The [[http://blog.golang.org/][Go Blog]] has a large archive of informative Go articles. 924 925 Visit [[http://golang.org][golang.org]] for more. 926