SlideShare a Scribd company logo
10〜30分で何となく分かるGo
#moriyoshi
10〜30分で何となく分かるGo
10〜30分で何となく分かるGo
10〜30分で何となく分かるGo
10〜30分で何となく分かるGo
10〜30分で何となく分かるGo
$ export GOROOT=$HOME/go
$ export GOBIN=$HOME/go/bin
$ export GOOS=linux darwin
$ export GOARCH=amd64 x86
$ export PATH=$GOBIN:$PATH
$ mkdir -p $GOBIN
$ hg clone -r release 
  https://go.googlecode.com/hg/ $GOROOT
$ cd $GOROOT/src
$ ./all.bash
package main
import "fmt"

func main() {
    fmt.Printf("   !");
}
$ export GOROOT=$HOME/go
$ export GOBIN=$HOME/go/bin
$ export GOOS=linux
$ export GOARCH=amd64
$ export PATH=$GOBIN:$PATH
$ 6g test.go
$ 6l -o test test.6
$ ./test
10〜30分で何となく分かるGo
10〜30分で何となく分かるGo
?
10〜30分で何となく分かるGo
10〜30分で何となく分かるGo
package main
import "fmt"

func main() {
    str := "       ";
    str += "   ";
    fmt.Printf("%sn", str);
}
package main
import "fmt"

func main() {
    arr := [4]int { 1, 2,   3, 4};
    fmt.Printf("0: %dn",   arr[0]);
    fmt.Printf("1: %dn",   arr[1]);
    fmt.Printf("2: %dn",   arr[2]);
    fmt.Printf("3: %dn",   arr[3]);
}
package main
import "fmt"

func main() {
    str1 := "Hello, world!";
    str2 := "        ,     ";
    fmt.Printf("%s (%d)n", str1, len(str1));
    fmt.Printf("%sn", str1[0:5]);
    fmt.Printf("%s (%d)n", str2, len(str2));
    fmt.Printf("%sn", str2[0:5]); // WTF!
}
package main
import "fmt"
import "utf8"

func main() {
    str1 := "Hello, world!";
    str2 := "        ,     ";
    fmt.Printf("%s (%d)n", str1, len(str1));
    fmt.Printf("%sn", str1[0:5]);
    fmt.Printf("%s (%d)n", str2,
               utf8.RuneCountInString(str2));
    // FIXME: utf8     substring
}
package main
import "fmt"

func main() {
    str := "Hello";

    for i, c := range str {
        fmt.Printf("%d: %cn", i, c);
    }
}
package main
import "fmt"

func main() {
    str := "Hello";

    for i := 0; i < len(str); i += 1 {
        fmt.Printf("> %cn", str[i]);
    }
}
package main
import "fmt"

func main() {
    str := "Hello";

    i := 0;
    for {
        if i >= len(str) {
            break
        }
        fmt.Printf("> %cn", str[i]);
        i += 1;
    }
}
package main
import "bufio"
import "os"
import "fmt"

func main() {
    in := bufio.NewReader(os.Stdin);

    for {
        str, e := in.ReadString('n');
        if e != nil {
            if e != os.EOF {
                fmt.Printf("Error: %sn", e);
            }
            break
        }
        os.Stdout.WriteString("-> ");
        os.Stdout.WriteString(str);
    }
}
package main
import "fmt"
import "regexp"

func main() {
    re, e := regexp.Compile("[A-Z][a-z]+");
    if e != nil {
        fmt.Printf("Error: %sn", e);
        return
    }
    fmt.Printf("%tn", re.MatchString("test"));
    matches := re.MatchStrings("Abc Def ");
    for i := range matches {
        fmt.Printf("%sn", matches[i]);
    }
    str := "test Test abc";
    fmt.Printf("%sn", re.ReplaceAllString(str , "***"));
}
package main
import (
    "io";
    "fmt";
    "http"
)

func main() {
    url := "http://search.twitter.com/search.json?q="
            + http.URLEscape("#moriyoshi");
    resp, _, e := http.Get(url);
    if e != nil { goto Error; }
    body, e := io.ReadAll(resp.Body);
    if e != nil { goto Error; }
    resp.Body.Close();
    fmt.Printf(">>> %sn", string(body));
    return;

Error:
    fmt.Printf("Error: %sn", e);
    return;
}
package main
import (
    "io";
    "fmt";
    "http";
    "json";
)

func jsonGet(url string) json.Json {
    resp, _, e := http.Get(url);
    if e != nil { goto Error; }
    body, e := io.ReadAll(resp.Body);
    if e != nil { goto Error; }
    resp.Body.Close();
    jsonObj, ok, etok := json.StringToJson(string(body));
    if !ok {
        fmt.Printf("JSON syntax error near: " + etok);
        return nil;
    }
    return jsonObj;
Error:
    fmt.Printf("Error: %sn", e);
    return nil;
}
func main() {
    url := "http://search.twitter.com/search.json?q="
            + http.URLEscape("#moriyoshi");
    j := jsonGet(url);
    results := json.Walk(j, "results");
    for i := 0; i < results.Len(); i += 1 {
        r := results.Elem(i);
        fmt.Printf("%s: %sn",
                    r.Get("from_user"),
                    r.Get("text"));
    }
    return;
}
package main
import (
    "fmt";
    "time";
)

func sub(n int) {
    fmt.Printf("Goroutine #%d started.n", n);
    for i := 0; i < 5; i += 1 {
        fmt.Printf("%d: %dn", n, i);
        time.Sleep(1e9);
    }
}

func main() {
    for i := 0; i < 10; i += 1 {
        go sub(i);
    }
    time.Sleep(5e9);
}
package main
import (
    "fmt";
    "time";
)

func sub(n int, ch chan int) {
    fmt.Printf("Goroutine #%d started.n",
n);
    for i := 0; i < 5; i += 1 {
        fmt.Printf("%d: %dn", n, i);
        time.Sleep(1e8);
    }
    ch <- n
}
func main() {
    ch := make(chan int);
    for n := 0; n < 10; n += 1 {
        go sub(n, ch);
        time.Sleep(4e8)
    }
    for i := 0; i < 10; i += 1 {
        n := <- ch;
        fmt.Printf("Goroutine #%d ended.
n", n)
    }
}
package main
import (
    "fmt";
)
type Employee struct {
    name string;
}
type Company struct {
    name string;
    employees []Employee;
}

func main() {
    c := Company { name:"Acme" };
    c.employees = []Employee {
       Employee { name:"Foo" },
       Employee { name:"Bar" }
    };

    fmt.Printf("Company name: %sn", c.name);
    fmt.Printf("Employees: %dn", len(c.employees));
    for _, employee := range c.employees {
        fmt.Printf("    %sn", employee.name);
    }
}
package main
import (
    "fmt";
)

func main() {
    m := make(map[string] string);
    m["Foo"] = "Hoge";
    m["Bar"] = "Fuga";
    for k, v := range m {
        fmt.Printf("%s: %sn", k, v)
    }
}
package main
import (
    "fmt";
)
type MyInt int;
type Foo struct {
    values []int;
}

func (self *Foo) sum() int {
    retval := 0;
    for _, v := range self.values {
        retval += v
    }
    return retval
}

func main() {
    f := &Foo { values: []int { 0, 1, 2, 3, 4 } };
    fmt.Printf("%dn", f.sum());
}
package main
import (
    "fmt";
)
type MyInt int;

func (self MyInt) add(rhs int) MyInt {
    return MyInt(int(self) + rhs)
}

func main() {
    fmt.Printf("%dn",
               MyInt(1).add(4).add(5));
}
package main
import (
    "fmt"
)

type IHello interface {
    sayHello()
}

type IKonnichiwa interface {
    sayKonnichiwa()
}

type IBilingual interface {
    IHello;
    IKonnichiwa
}
type TypeA int;
type TypeB int;
type TypeC int;

func (_ TypeA) sayHello() {}

func (_ TypeB) sayKonnichiwa() {}

func (_ TypeC) sayHello() {}

func (_ TypeC) sayKonnichiwa() {}

func hello(_ IHello) {
    fmt.Printf("Hellon")
}
func konnichiwa(_ IKonnichiwa) {
    fmt.Printf("Konnichiwan")
}
func main() {
    var (
        a TypeA;
        b TypeB;
        c TypeC
    );

    hello(a);
    konnichiwa(b);
    hello(c);
    konnichiwa(c);
}
package main

type Foo struct {
    a int
}
type Bar struct {
    b int
}
type FuBar struct {
    *Foo;
    *Bar
}
func (_ *Foo) doSomething() {}

func (_ *Bar) doIt() {}

func main() {
    fubar := new(FuBar);
    fubar.doSomething();
    fubar.doIt()
}
package main

import "fmt";

func main() {
    fmt.Printf("%dn",
        func(f func(func(int) int) int) int {
            return f(func(a int) int { return a + 2 })
        }(func(g func(int) int) int { return g(1) }));
}
package main
import "fmt"

type UntypedFunc func(Any) Any;
type Any struct {
    UntypedFunc;
    int
}

func main() {
    // Y-combinator
    result := func(f Any) Any {
        return func(x Any) Any {
            return f.UntypedFunc(
                Any{ UntypedFunc: func(y Any) Any {
                    return x.UntypedFunc(x).UntypedFunc(y)
                } } )
        }(
            Any{ UntypedFunc: func(x Any) Any {
                return f.UntypedFunc(
                    Any{ UntypedFunc: func(y Any) Any {
                        return x.UntypedFunc(x).UntypedFunc(y)
                    } } )
            } }
        );
    }(Any{ UntypedFunc: func(f Any) Any {
        return Any{ UntypedFunc: func(n Any) Any {
            if (n.int == 0) {
                return Any{ int: 1 }
            }
            return Any{ int: f.UntypedFunc(Any{ int: n.int - 1 }).int * n.int }
        } }
    } } );
    fmt.Printf("%dn", result.UntypedFunc(Any{ int: 5 }).int);
}
package main

import "fmt";

func sliceInfo(arr []int) {
    fmt.Printf("len(arr)=%dn", len(arr));
    fmt.Printf("cap(arr)=%dn", cap(arr));
}

func arrayInfo(arr *[4]int) {
    fmt.Printf("len(arr)=%dn", len(arr));
    fmt.Printf("cap(arr)=%dn", cap(arr));
}

func main() {
    arr := [4]int { 1, 2, 3, 4 };
    arrayInfo(&arr);
    // doesn't compile
    // sliceInfo(arr);
    sliceInfo(&arr);
    // doesn't compile
    // arrayInfo(arr[0:2]);
    sliceInfo(arr[0:2])
}
10〜30分で何となく分かるGo

More Related Content

10〜30分で何となく分かるGo

  • 8. $ export GOROOT=$HOME/go $ export GOBIN=$HOME/go/bin $ export GOOS=linux darwin $ export GOARCH=amd64 x86 $ export PATH=$GOBIN:$PATH $ mkdir -p $GOBIN $ hg clone -r release https://go.googlecode.com/hg/ $GOROOT $ cd $GOROOT/src $ ./all.bash
  • 9. package main import "fmt" func main() { fmt.Printf(" !"); }
  • 10. $ export GOROOT=$HOME/go $ export GOBIN=$HOME/go/bin $ export GOOS=linux $ export GOARCH=amd64 $ export PATH=$GOBIN:$PATH $ 6g test.go $ 6l -o test test.6 $ ./test
  • 13. ?
  • 16. package main import "fmt" func main() { str := " "; str += " "; fmt.Printf("%sn", str); }
  • 17. package main import "fmt" func main() { arr := [4]int { 1, 2, 3, 4}; fmt.Printf("0: %dn", arr[0]); fmt.Printf("1: %dn", arr[1]); fmt.Printf("2: %dn", arr[2]); fmt.Printf("3: %dn", arr[3]); }
  • 18. package main import "fmt" func main() { str1 := "Hello, world!"; str2 := " , "; fmt.Printf("%s (%d)n", str1, len(str1)); fmt.Printf("%sn", str1[0:5]); fmt.Printf("%s (%d)n", str2, len(str2)); fmt.Printf("%sn", str2[0:5]); // WTF! }
  • 19. package main import "fmt" import "utf8" func main() { str1 := "Hello, world!"; str2 := " , "; fmt.Printf("%s (%d)n", str1, len(str1)); fmt.Printf("%sn", str1[0:5]); fmt.Printf("%s (%d)n", str2, utf8.RuneCountInString(str2)); // FIXME: utf8 substring }
  • 20. package main import "fmt" func main() { str := "Hello"; for i, c := range str { fmt.Printf("%d: %cn", i, c); } }
  • 21. package main import "fmt" func main() { str := "Hello"; for i := 0; i < len(str); i += 1 { fmt.Printf("> %cn", str[i]); } }
  • 22. package main import "fmt" func main() { str := "Hello"; i := 0; for { if i >= len(str) { break } fmt.Printf("> %cn", str[i]); i += 1; } }
  • 23. package main import "bufio" import "os" import "fmt" func main() { in := bufio.NewReader(os.Stdin); for { str, e := in.ReadString('n'); if e != nil { if e != os.EOF { fmt.Printf("Error: %sn", e); } break } os.Stdout.WriteString("-> "); os.Stdout.WriteString(str); } }
  • 24. package main import "fmt" import "regexp" func main() { re, e := regexp.Compile("[A-Z][a-z]+"); if e != nil { fmt.Printf("Error: %sn", e); return } fmt.Printf("%tn", re.MatchString("test")); matches := re.MatchStrings("Abc Def "); for i := range matches { fmt.Printf("%sn", matches[i]); } str := "test Test abc"; fmt.Printf("%sn", re.ReplaceAllString(str , "***")); }
  • 25. package main import ( "io"; "fmt"; "http" ) func main() { url := "http://search.twitter.com/search.json?q=" + http.URLEscape("#moriyoshi"); resp, _, e := http.Get(url); if e != nil { goto Error; } body, e := io.ReadAll(resp.Body); if e != nil { goto Error; } resp.Body.Close(); fmt.Printf(">>> %sn", string(body)); return; Error: fmt.Printf("Error: %sn", e); return; }
  • 26. package main import ( "io"; "fmt"; "http"; "json"; ) func jsonGet(url string) json.Json { resp, _, e := http.Get(url); if e != nil { goto Error; } body, e := io.ReadAll(resp.Body); if e != nil { goto Error; } resp.Body.Close(); jsonObj, ok, etok := json.StringToJson(string(body)); if !ok { fmt.Printf("JSON syntax error near: " + etok); return nil; } return jsonObj; Error: fmt.Printf("Error: %sn", e); return nil; }
  • 27. func main() { url := "http://search.twitter.com/search.json?q=" + http.URLEscape("#moriyoshi"); j := jsonGet(url); results := json.Walk(j, "results"); for i := 0; i < results.Len(); i += 1 { r := results.Elem(i); fmt.Printf("%s: %sn", r.Get("from_user"), r.Get("text")); } return; }
  • 28. package main import ( "fmt"; "time"; ) func sub(n int) { fmt.Printf("Goroutine #%d started.n", n); for i := 0; i < 5; i += 1 { fmt.Printf("%d: %dn", n, i); time.Sleep(1e9); } } func main() { for i := 0; i < 10; i += 1 { go sub(i); } time.Sleep(5e9); }
  • 29. package main import ( "fmt"; "time"; ) func sub(n int, ch chan int) { fmt.Printf("Goroutine #%d started.n", n); for i := 0; i < 5; i += 1 { fmt.Printf("%d: %dn", n, i); time.Sleep(1e8); } ch <- n }
  • 30. func main() { ch := make(chan int); for n := 0; n < 10; n += 1 { go sub(n, ch); time.Sleep(4e8) } for i := 0; i < 10; i += 1 { n := <- ch; fmt.Printf("Goroutine #%d ended. n", n) } }
  • 31. package main import ( "fmt"; ) type Employee struct { name string; } type Company struct { name string; employees []Employee; } func main() { c := Company { name:"Acme" }; c.employees = []Employee { Employee { name:"Foo" }, Employee { name:"Bar" } }; fmt.Printf("Company name: %sn", c.name); fmt.Printf("Employees: %dn", len(c.employees)); for _, employee := range c.employees { fmt.Printf(" %sn", employee.name); } }
  • 32. package main import ( "fmt"; ) func main() { m := make(map[string] string); m["Foo"] = "Hoge"; m["Bar"] = "Fuga"; for k, v := range m { fmt.Printf("%s: %sn", k, v) } }
  • 33. package main import ( "fmt"; ) type MyInt int; type Foo struct { values []int; } func (self *Foo) sum() int { retval := 0; for _, v := range self.values { retval += v } return retval } func main() { f := &Foo { values: []int { 0, 1, 2, 3, 4 } }; fmt.Printf("%dn", f.sum()); }
  • 34. package main import ( "fmt"; ) type MyInt int; func (self MyInt) add(rhs int) MyInt { return MyInt(int(self) + rhs) } func main() { fmt.Printf("%dn", MyInt(1).add(4).add(5)); }
  • 35. package main import ( "fmt" ) type IHello interface { sayHello() } type IKonnichiwa interface { sayKonnichiwa() } type IBilingual interface { IHello; IKonnichiwa }
  • 36. type TypeA int; type TypeB int; type TypeC int; func (_ TypeA) sayHello() {} func (_ TypeB) sayKonnichiwa() {} func (_ TypeC) sayHello() {} func (_ TypeC) sayKonnichiwa() {} func hello(_ IHello) { fmt.Printf("Hellon") } func konnichiwa(_ IKonnichiwa) { fmt.Printf("Konnichiwan") }
  • 37. func main() { var ( a TypeA; b TypeB; c TypeC ); hello(a); konnichiwa(b); hello(c); konnichiwa(c); }
  • 38. package main type Foo struct { a int } type Bar struct { b int } type FuBar struct { *Foo; *Bar }
  • 39. func (_ *Foo) doSomething() {} func (_ *Bar) doIt() {} func main() { fubar := new(FuBar); fubar.doSomething(); fubar.doIt() }
  • 40. package main import "fmt"; func main() { fmt.Printf("%dn", func(f func(func(int) int) int) int { return f(func(a int) int { return a + 2 }) }(func(g func(int) int) int { return g(1) })); }
  • 41. package main import "fmt" type UntypedFunc func(Any) Any; type Any struct { UntypedFunc; int } func main() { // Y-combinator result := func(f Any) Any { return func(x Any) Any { return f.UntypedFunc( Any{ UntypedFunc: func(y Any) Any { return x.UntypedFunc(x).UntypedFunc(y) } } ) }( Any{ UntypedFunc: func(x Any) Any { return f.UntypedFunc( Any{ UntypedFunc: func(y Any) Any { return x.UntypedFunc(x).UntypedFunc(y) } } ) } } ); }(Any{ UntypedFunc: func(f Any) Any { return Any{ UntypedFunc: func(n Any) Any { if (n.int == 0) { return Any{ int: 1 } } return Any{ int: f.UntypedFunc(Any{ int: n.int - 1 }).int * n.int } } } } } ); fmt.Printf("%dn", result.UntypedFunc(Any{ int: 5 }).int); }
  • 42. package main import "fmt"; func sliceInfo(arr []int) { fmt.Printf("len(arr)=%dn", len(arr)); fmt.Printf("cap(arr)=%dn", cap(arr)); } func arrayInfo(arr *[4]int) { fmt.Printf("len(arr)=%dn", len(arr)); fmt.Printf("cap(arr)=%dn", cap(arr)); } func main() { arr := [4]int { 1, 2, 3, 4 }; arrayInfo(&arr); // doesn't compile // sliceInfo(arr); sliceInfo(&arr); // doesn't compile // arrayInfo(arr[0:2]); sliceInfo(arr[0:2]) }