Last active
August 29, 2015 14:25
-
-
Save karlmutch/aa30cfaf6ee1f3750e57 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // string and rune | |
| const sample = "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98" | |
| fmt.Printf("%x\n", sample) "bdb23dbc20e28c98" | |
| fmt.Printf("% x\n", sample) "bd b2 3d bc 20 e2 8c 98" | |
| fmt.Printf("%q\n", sample) "\xbd\xb2=\xbc ⌘" | |
| fmt.Printf("%+q\n", sample) "\xbd\xb2=\xbc \u2318" | |
| const nihongo = "日本語" | |
| for index, runeValue := range nihongo { | |
| fmt.Printf("%#U starts at byte position %d\n", runeValue, index) | |
| } | |
| const nihongo = "日本語" | |
| for i, w := 0, 0; i < len(nihongo); i += w { | |
| runeValue, width := utf8.DecodeRuneInString(nihongo[i:]) | |
| fmt.Printf("%#U starts at byte position %d\n", runeValue, i) | |
| w = width | |
| } | |
| source := []rune(string("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")) | |
| // Error Handling | |
| type ErrNegativeSqrt float64 | |
| func (e ErrNegativeSqrt) Error() string { | |
| return (fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))) | |
| } | |
| func Sqrt(x float64) (float64, error) { | |
| if x < 0 { | |
| return 0, ErrNegativeSqrt(x) | |
| } | |
| return math.Sqrt(x), nil | |
| } | |
| // Functors and type behaviors | |
| package main | |
| import ( | |
| "fmt" | |
| "log" | |
| "net/http" | |
| ) | |
| type String string | |
| type Struct struct { | |
| Greeting string | |
| Punct string | |
| Who string | |
| } | |
| func (s Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
| fmt.Fprintf(w, "%v%v%v", s.Greeting, s.Punct, s.Who) | |
| } | |
| func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
| if _, error := fmt.Fprint(w, s); error != nil { | |
| // Something | |
| } | |
| } | |
| func main() { | |
| http.Handle("/string", String("I'm a frayed knot.")) | |
| http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"}) | |
| err := http.ListenAndServe("localhost:4000", nil) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| } | |
| // Concurrency, closure, tuple style assignments | |
| package main | |
| import "fmt" | |
| func sum(a []int, c chan int) { | |
| sum := 0 | |
| for _, v := range a { | |
| sum += v | |
| } | |
| c <- sum // send sum 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) | |
| } | |
| // Simulated tree | |
| package main | |
| import ( | |
| "fmt" | |
| "reflect" | |
| "golang.org/x/tour/tree" | |
| ) | |
| // Walk walks the tree t sending all values | |
| // from the tree to the channel ch. | |
| func Walk(t *tree.Tree, ch chan int) { | |
| if nil != t.Left { | |
| Walk(t.Left, ch) | |
| } | |
| ch <- t.Value | |
| if nil != t.Right { | |
| Walk(t.Right, ch) | |
| } | |
| } | |
| // Same determines whether the trees | |
| // t1 and t2 contain the same values. | |
| func Same(t1, t2 *tree.Tree) bool { | |
| t1Values, t2Values := make([]int, 0), make([]int, 0) | |
| t1chan, t2chan := make(chan int, 5), make(chan int, 5) | |
| t1Done := false | |
| t2Done := false | |
| go func() { | |
| Walk(t1, t1chan) | |
| t1Done = true | |
| }() | |
| go func() { | |
| Walk(t2, t2chan) | |
| t2Done = true | |
| }() | |
| for t1Done == false && t2Done == false { | |
| select { | |
| case t1val := <-t1chan: | |
| t1Values = append(t1Values, t1val) | |
| case t2val := <-t2chan: | |
| t2Values = append(t2Values, t2val) | |
| } | |
| } | |
| return reflect.DeepEqual(t1Values, t2Values) | |
| } | |
| func main() { | |
| ch := make(chan int, 5) | |
| t := tree.New(1) | |
| go Walk(t, ch) | |
| items := 0 | |
| for { | |
| select { | |
| case Value := <-ch: | |
| items++ | |
| if Value != items { | |
| fmt.Println("Test 1 failed") | |
| } | |
| if items == 10 { | |
| return | |
| } | |
| } | |
| } | |
| if Same(tree.New(1), tree.New(2)) { | |
| fmt.Println("Test 2 failed") | |
| } | |
| if !Same(tree.New(6), tree.New(6)) { | |
| fmt.Println("Test 3 failed") | |
| } | |
| } | |
| // Crawler with wait group workers | |
| package main | |
| import ( | |
| "fmt" | |
| "sync" | |
| ) | |
| type Fetcher interface { | |
| // Fetch returns the body of URL and | |
| // a slice of URLs found on that page. | |
| Fetch(url string) (body string, urls []string, err error) | |
| } | |
| var urlsDone = struct { | |
| sync.RWMutex // Anonymous | |
| m map[string]bool | |
| } {m : make(map[string]bool)} | |
| var wg sync.WaitGroup | |
| // Crawl uses fetcher to recursively crawl | |
| // pages starting with url, to a maximum of depth. | |
| func Crawl(url string, depth int, fetcher Fetcher) { | |
| if depth <= 0 { | |
| return | |
| } | |
| urlsDone.RLock() | |
| _, ok := urlsDone.m[url] | |
| urlsDone.RUnlock() | |
| if ok { | |
| return; | |
| } | |
| urlsDone.Lock() | |
| urlsDone.m[url] = true | |
| urlsDone.Unlock() | |
| body, urls, err := fetcher.Fetch(url) | |
| if err != nil { | |
| fmt.Println(err) | |
| return | |
| } | |
| fmt.Printf("found: %s %q with %v links\n", url, body, len(urls)) | |
| wg.Add(len(urls)) | |
| for _, u := range urls { | |
| go func (aUrl string) { | |
| defer wg.Done() | |
| Crawl(aUrl, depth-1, fetcher) | |
| }(u) | |
| } | |
| return | |
| } | |
| func main() { | |
| wg.Add(1) | |
| go func () { | |
| Crawl("http://golang.org/", 4, fetcher) | |
| wg.Done() | |
| }() | |
| wg.Wait() | |
| } | |
| // fakeFetcher is Fetcher that returns canned results. | |
| type fakeFetcher map[string]*fakeResult | |
| type fakeResult struct { | |
| body string | |
| urls []string | |
| } | |
| func (f fakeFetcher) Fetch(url string) (string, []string, error) { | |
| if res, ok := f[url]; ok { | |
| return res.body, res.urls, nil | |
| } | |
| return "", nil, fmt.Errorf("not found: %s", url) | |
| } | |
| // fetcher is a populated fakeFetcher. | |
| var fetcher = fakeFetcher{ | |
| "http://golang.org/": &fakeResult{ | |
| "The Go Programming Language", | |
| []string{ | |
| "http://golang.org/pkg/", | |
| "http://golang.org/cmd/", | |
| }, | |
| }, | |
| "http://golang.org/pkg/": &fakeResult{ | |
| "Packages", | |
| []string{ | |
| "http://golang.org/", | |
| "http://golang.org/cmd/", | |
| "http://golang.org/pkg/fmt/", | |
| "http://golang.org/pkg/os/", | |
| }, | |
| }, | |
| "http://golang.org/pkg/fmt/": &fakeResult{ | |
| "Package fmt", | |
| []string{ | |
| "http://golang.org/", | |
| "http://golang.org/pkg/", | |
| }, | |
| }, | |
| "http://golang.org/pkg/os/": &fakeResult{ | |
| "Package os", | |
| []string{ | |
| "http://golang.org/", | |
| "http://golang.org/pkg/", | |
| }, | |
| }, | |
| } | |
| // Other patterns have functions returning channels for go functions they initiate | |
| func boring(msg string) <-chan string { // Returns receive-only channel of strings. | |
| c := make(chan string) | |
| go func() { // We launch the goroutine from inside the function. | |
| for i := 0; ; i++ { | |
| c <- fmt.Sprintf("%s %d", msg, i) | |
| time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond) | |
| } | |
| }() | |
| return c // Return the channel to the caller. | |
| } | |
| // Fan in | |
| func fanIn(input1, input2 <-chan string) <-chan string { | |
| c := make(chan string) | |
| go func() { for { c <- <-input1 } }() | |
| go func() { for { c <- <-input2 } }() | |
| return c | |
| } | |
| // Or alternatively | |
| func fanIn(input1, input2 <-chan string) <-chan string { | |
| c := make(chan string) | |
| go func() { | |
| for { | |
| select { | |
| case s := <-input1: c <- s | |
| case s := <-input2: c <- s | |
| } | |
| } | |
| }() | |
| return c | |
| } | |
| func main() { | |
| c := fanIn(boring("Joe"), boring("Ann")) | |
| for i := 0; i < 10; i++ { | |
| fmt.Println(<-c) | |
| } | |
| fmt.Println("You're both boring; I'm leaving.") | |
| } | |
| // Channels can be sent within messages | |
| type Message struct { | |
| str string | |
| wait chan bool | |
| } | |
| for i := 0; i < 5; i++ { | |
| msg1 := <-c; fmt.Println(msg1.str) | |
| msg2 := <-c; fmt.Println(msg2.str) | |
| msg1.wait <- true | |
| msg2.wait <- true | |
| } | |
| waitForIt := make(chan bool) // Shared between all messages. | |
| c <- Message{ fmt.Sprintf("%s: %d", msg, i), waitForIt } | |
| time.Sleep(time.Duration(rand.Intn(2e3)) * time.Millisecond) | |
| <-waitForIt | |
| // Daisy chaining | |
| func f(left, right chan int) { | |
| left <- 1 + <-right | |
| } | |
| func main() { | |
| const n = 10000 | |
| leftmost := make(chan int) | |
| right := leftmost | |
| left := leftmost | |
| for i := 0; i < n; i++ { | |
| right = make(chan int) | |
| go f(left, right) | |
| left = right | |
| } | |
| go func(c chan int) { c <- 1 }(right) | |
| fmt.Println(<-leftmost) | |
| } | |
| // Asynchronously use the first result of n number of actions | |
| func First(query string, replicas ...Search) Result { | |
| c := make(chan Result) | |
| searchReplica := func(i int) { c <- replicas[i](query) } | |
| for i := range replicas { | |
| go searchReplica(i) | |
| } | |
| return <-c | |
| } | |
| c := make(chan Result) | |
| go func() { c <- First(query, Web1, Web2) } () | |
| go func() { c <- First(query, Image1, Image2) } () | |
| go func() { c <- First(query, Video1, Video2) } () | |
| timeout := time.After(80 * time.Millisecond) | |
| for i := 0; i < 3; i++ { | |
| select { | |
| case result := <-c: | |
| results = append(results, result) | |
| case <-timeout: | |
| fmt.Println("timed out") | |
| return | |
| } | |
| } | |
| return | |
| // Quitting using Close | |
| func worker(i int, ch chan Work, quit chan struct{}) { | |
| var quitting bool | |
| for { | |
| select { | |
| case w := <-ch: | |
| if quitting { | |
| w.Refuse(); fmt.Println("worker", i, "refused", w) | |
| break | |
| } | |
| w.Do(); fmt.Println("worker", i, "processed", w) | |
| case <-quit: | |
| fmt.Println("worker", i, "quitting") | |
| quitting = true | |
| } | |
| } | |
| } | |
| func main() { | |
| ch, quit := make(chan Work), make(chan struct{}) | |
| go makeWork(ch) | |
| for i := 0; i < 4; i++ { go worker(i, ch, quit) } | |
| time.Sleep(5 * time.Second) | |
| close(quit) | |
| time.Sleep(2 * time.Second) | |
| } | |
| // |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment