Last active
April 4, 2017 03:37
-
-
Save oyakata/173e134931414786a0b9d1ceab6e4e16 to your computer and use it in GitHub Desktop.
型付きfuncのスライスに所定の構造体のメソッドでも渡せることをテスト
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
package main | |
import ( | |
"fmt" | |
) | |
// Foo.<method>がFuncのインターフェースを満たす。 | |
// Foo.Get, Foo.Incrで同じキーを参照する。 | |
type Data struct { | |
Name string | |
Score int | |
Tags []string | |
status string | |
} | |
func (d *Data) Stop() { | |
d.status = "stop" | |
} | |
func NewData() *Data { | |
return &Data{ | |
Name: "<名無し>", | |
Score: 0, | |
Tags: []string{}, | |
status: "doing", | |
} | |
} | |
type Func func(x, y, z int, data *Data) | |
type Block []Func | |
func (funcs Block) ApplyAll(x, y, z int, data *Data) { | |
for _, fn := range funcs { | |
if data.status == "stop" { | |
break | |
} | |
fn(x, y, z, data) | |
} | |
} | |
type Foo struct { | |
GroupName string | |
} | |
func (f *Foo) Incr(x, y, z int, data *Data) { | |
score := x + y + z | |
data.Name = fmt.Sprintf("*** %v: x = %v, y = %v, z = %v => %v ***", | |
f.GroupName, | |
x, y, z, | |
score) | |
data.Score += score | |
data.Tags = append(data.Tags, "Foo.Incr") | |
} | |
func (f *Foo) Get(x, y, z int, data *Data) { | |
if z >= 3 { | |
data.Stop() | |
} | |
data.Score += z | |
data.Tags = append(data.Tags, "Foo.Get") | |
} | |
func main() { | |
var ( | |
block Block | |
data *Data | |
) | |
foo := &Foo{"チャーリ〜"} | |
block = Block{foo.Incr, foo.Get} // block = []Func{foo.Incr, foo.Get} でも可 | |
data = NewData() | |
block.ApplyAll(1, 2, 3, data) | |
fmt.Printf("Name = %v\nScore = %v\nTags = %v\n", data.Name, data.Score, data.Tags) | |
block = Block{foo.Get, foo.Incr} | |
data = NewData() | |
block.ApplyAll(1, 2, 3, data) | |
fmt.Printf("Name = %v\nScore = %v\nTags = %v\n", data.Name, data.Score, data.Tags) | |
// Name = *** チャーリ〜: x = 1, y = 2, z = 3 => 6 *** | |
// Score = 9 | |
// Tags = [Foo.Incr Foo.Get] | |
// Name = <名無し> | |
// Score = 3 | |
// Tags = [Foo.Get] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Data.statusをintに変えると、Funcの方で自分の実行を取止めるか否か判断可能になる。