1. エキスパートGo
The Go gopher was designed by Renee French.
The gopher stickers was made by Takuya Ueda.
Licensed under the Creative Commons 3.0
Attributions license. 1
更新日:2017/08/08
28. // 組み込み型を基にする
type Int int
// 他のパッケージの型を基にする
type MyWriter io.Writer
// 型リテラルに基にする
type Person struct {
Name string
}
typeを使った型の作成
type <型名> <型リテラル>|<型名>
28
intとIntは別の型として扱われる
42. 型スイッチ
型によって処理をスイッチする
42
var i interface{}
i = 100
switch v := i.(type) {
case int:
fmt.Println(v*2)
case string:
fmt.Println(v+"hoge")
default:
fmt.Println("default")
}
Playgroundで動かす
84. ゴールーチン間のデータ競合 −2−
84
n := 1
go func() {
for i := 2; i <= 5; i++ {
fmt.Println(n, "*", i)
n *= i
time.Sleep(100)
}
}()
http://play.golang.org/p/yqk82u0E4V
for i := 1; i <= 10; i++ {
fmt.Println(n, "+", i)
n += 1
time.Sleep(100)
}
競合
85. データ競合の解決
■ 問題点
● どのゴールーチンが先にアクセスするか分からない
● 値の変更や参照が競合する
■ 解決方法
● 1つの変数には1つのゴールーチンからアクセスする
● チャネルを使ってゴールーチン間で通信をする
● またはロックをとる(syncパッケージ)
85
"Do not communicate by sharing memory; instead,
share memory by communicating"