いまさらGo言語に手つけてみた: The Go Program Language - Course Notes

Documentation - The Go Programming Language

Course Notes

Slides from a 3-day course about the Go programming language. A more thorough introduction than the tutorial.

先週の平日、ふと思い立って、夜な夜なGo言語の環境構築してA Tour of Goをざっとやってみたんですが、3連休は3-Dayコースを消化してみよう、とそういう話です。

この際、超訳とかするのもありなんですが、めんどgolang.jp - プログラミング言語Goの情報サイトにありそーな気がするのでやりません。

ということで、以下は個人メモ追記していきます。

資料はRob Pikeが作成

  • メアドがr@google.comって一文字かいw

Go Course Day 1

Exercise:

You all know what the Fibonacci series is. Write a package to implement it. There should be a function to get the next value. (You don't have structs yet; can you find a way to save state without globals?) But instead of addition, make the operation settable by a function provided by the user. Integers? Floats? Strings? Up to you.

とりあえずはこんなんでOKかな??

func NextFibonacci() func() int {
        x := 0
        y := 0
        return func() (ret int) {
                if x+y == 0 {
                        ret = 1
                } else {
                        ret = x + y
                }
                x, y = y, ret
                return ret
        }
}

Go Course Day 2

Anonymous fields:

Inside a struct, you can declare fields, such as another struct, without giving a name for the field. These are called anonymous fields and they act as if the inner struct is simply inserted or "embedded" into the outer.

これ、Go言語における構造体をネストしてない構造体

type Foo struct {
        x, y int
}

f := Foo{1, 2}

C言語よろしくf.x、f.yでフィールドを参照するんですが、ネストしたものは

type Bar struct {
        Foo
        z int
}

b := Bar{Foo{1, 2}, 3}

のように記述してb.x、b.y、b.zと参照できます。"Anonymous"ってネーミングからだけだといまいちピンと来ないんだけど、こーゆーことらしいです。このAnonymous fields、単なる糖衣構文かと思いきや非常におもしろいのが、Go言語における型の派生を担う文法となってるところ。