add english version

This commit is contained in:
astaxie
2014-05-10 18:05:31 +08:00
parent 946300f0b1
commit eb5220f7eb
269 changed files with 16101 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
// Example code for Chapter 2.7 from "Build Web Application with Golang"
// Purpose: Shows how to use a buffered channel
package main
import "fmt"
func main() {
c := make(chan int, 2) // change 2 to 1 will have runtime error, but 3 is fine
c <- 1
c <- 2
fmt.Println(<-c)
fmt.Println(<-c)
}

View File

@@ -0,0 +1,20 @@
// Example code for Chapter 2.7 from "Build Web Application with Golang"
// Purpose: Shows how to launch a simple gorountine
package main
import (
"fmt"
"runtime"
)
func say(s string) {
for i := 0; i < 5; i++ {
runtime.Gosched()
fmt.Println(s)
}
}
func main() {
go say("world") // create a new goroutine
say("hello") // current goroutine
}

View File

@@ -0,0 +1,24 @@
// Example code for Chapter 2.7 from "Build Web Application with Golang"
// Purpose: Shows how to close and interate through a channel
package main
import (
"fmt"
)
func fibonacci(n int, c chan int) {
x, y := 1, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}
func main() {
c := make(chan int, 10)
go fibonacci(cap(c), c)
for i := range c {
fmt.Println(i)
}
}

View File

@@ -0,0 +1,30 @@
// Example code for Chapter 2.7 from "Build Web Application with Golang"
// Purpose: Shows how to use `select`
package main
import "fmt"
func fibonacci(c, quit chan int) {
x, y := 1, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
}
}
func main() {
c := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
quit <- 0
}()
fibonacci(c, quit)
}

View File

@@ -0,0 +1,27 @@
// Example code for Chapter 2.7 from "Build Web Application with Golang"
// Purpose: Shows how to create and use a timeout
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int)
o := make(chan bool)
go func() {
for {
select {
case v := <-c:
fmt.Println(v)
case <-time.After(5 * time.Second):
fmt.Println("timeout")
o <- true
break
}
}
}()
<-o
}

View File

@@ -0,0 +1,24 @@
// Example code for Chapter 2.7 from "Build Web Application with Golang"
// Purpose: Shows how to create and use a unbuffered channel
package main
import "fmt"
func sum(a []int, c chan int) {
total := 0
for _, v := range a {
total += v
}
c <- total // send total to c
}
func main() {
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}