A Tour of Go
Welcome!
Packages, variables, and functions.
Flow control statements: for, if, else, switch and defer
code:go
package main
import "fmt"
func Sqrt(x float64) float64 {
z := 1.0
for i := 0; i < 10; i++ {
prev := z
z -= (z*z - x) / (2 * z)
if -0.000000000000001 < prev-z && prev-z < 0.000000000000001 {
return z
}
}
return z
}
func main() {
fmt.Println(Sqrt(2))
}
Newton 法
適切な函數$ fに對して漸化式を$ z_{n+1}=z_n-\frac{f(z_n)}{f'(z_n)}とすると$ \lim_{n\to\infty}f(z_n)=0となり$ f(z)の零點を求められる
$ \sqrt xは$ z^2-x=0の解だから、$ f(z)=z^2-xの零點を求めたい。$ z_{n+1}=z_n-\frac{z_n^2-x}{2z_n}が計算する漸化式である
標準 library の math.Sqrt() は src/math/sqrt.go に定義してある。FreeBSD 由來の實裝
CPU が平方根を實裝して有れば src/math/sqrt_*.s それを使ふ
無ければ、Bit by bit method using integer arithmetic. (Slow, but portable)
1. Normalization
2. Bit by bit computation
3. Final rounding
More types: structs, slices, and maps.
code:go
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
pic := make([][]uint8, dx)
for x := 0; x < dx; x++ {
for y := 0; y < dy; y++ {
}
}
return pic
}
func main() {
pic.Show(Pic)
}
code:go
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
pic := make([][]uint8, dx)
for x, _ := range pic {
}
}
return pic
}
func main() {
pic.Show(Pic)
}
code:go
package main
import (
"strings"
"golang.org/x/tour/wc"
)
func WordCount(s string) mapstringint { for _, word := range strings.Fields(s) {
}
return result
}
func main() {
wc.Test(WordCount)
}
code:go
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
n1, n2 := 0, 1
return func() int {
n := n1
n1, n2 = n2, n1+n2
return n
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
Methods and interfaces
code:go
package main
import "fmt"
func (ipAddr IPAddr) String() string {
return fmt.Sprintf("%d.%d.%d.%d", ipAddr0, ipAddr1, ipAddr2, ipAddr3) }
func main() {
"loopback": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for name, ip := range hosts {
fmt.Printf("%v: %s\n", name, ip.String())
}
}
code:go
package main
import (
"fmt"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %f", e)
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
z := 1.0
for i := 0; i < 10; i++ {
prev := z
z -= (z*z - x) / (2 * z)
if -0.000000000000001 < prev-z && prev-z < 0.000000000000001 {
return z, nil
}
}
return z, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
code:go
package main
import "golang.org/x/tour/reader"
type MyReader struct{}
func (r MyReader) Read(b []byte) (int, error) {
return 1, nil
}
func main() {
reader.Validate(MyReader{})
}
code:go
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func (r rot13Reader) Read(b []byte) (int, error) {
b2 := make([]byte, cap(b))
n, err := r.r.Read(b2)
if err != nil {
return 0, err
}
for i := 0; i < n; i++ {
if 'A' <= b2i && b2i <= 'Z' { bi = (b2i-'A'+13)%26 + 'A' } else if 'a' <= b2i && b2i <= 'z' { bi = (b2i-'a'+13)%26 + 'a' } else {
}
}
return n, nil
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
$ echo -n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' | tr A-Za-z N-ZA-Mn-za-m
Vim.icon選擇 mode で g?
code:go
package main
import (
"image"
"image/color"
"golang.org/x/tour/pic"
)
type Image struct{}
func (img Image) ColorModel() color.Model {
return color.RGBAModel
}
func (img Image) Bounds() image.Rectangle {
return image.Rect(0, 0, 255, 255)
}
func (img Image) At(x, y int) color.Color {
return color.RGBA{uint8((x + y) / 2), uint8(x * y), uint8(x ^ y), 255}
}
func main() {
m := Image{}
pic.ShowImage(m)
}
Generics
Concurrency
code:go
package main
import (
"fmt"
"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 t.Left != nil {
Walk(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
Walk(t.Right, ch)
}
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int)
ch2 := make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
for i := 0; i < 10; i++ {
if <-ch1 != <-ch2 {
return false
}
}
return true
}
func main() {
ch := make(chan int)
go Walk(tree.New(1), ch)
for i := 0; i < 10; i++ {
fmt.Println(<-ch)
}
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}
code:go
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)
}
type Cache struct {
mu sync.Mutex
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, c Cache, fetcher Fetcher, wg *sync.WaitGroup) {
defer wg.Done()
c.mu.Lock()
return
}
c.mu.Unlock()
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q\n", url, body)
for _, u := range urls {
wg.Add(1)
go Crawl(u, c, fetcher, wg)
}
}
func main() {
wg := new(sync.WaitGroup)
wg.Add(1)
wg.Wait()
}
// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher mapstring*fakeResult type fakeResult struct {
body string
urls []string
}
func (f fakeFetcher) Fetch(url string) (string, []string, error) {
return res.body, res.urls, nil
}
return "", nil, fmt.Errorf("not found: %s", url)
}
// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
"The Go Programming Language",
[]string{
},
},
"Packages",
[]string{
},
},
"Package fmt",
[]string{
},
},
"Package os",
[]string{
},
},
}