walk: handle channels

This commit is contained in:
Muyao CHEN 2024-09-20 21:00:47 +02:00
parent 574532f484
commit ab7818e9ea
2 changed files with 25 additions and 0 deletions

View File

@ -27,6 +27,14 @@ func Walk(x interface{}, fn func(string)) {
for _, key := range val.MapKeys() {
walkValue(val.MapIndex(key))
}
case reflect.Chan:
for {
if v, ok := val.Recv(); ok {
walkValue(v)
} else {
break
}
}
}
}

View File

@ -98,6 +98,23 @@ func TestWalk(t *testing.T) {
assertContains(t, got, "meuh")
assertContains(t, got, "meh")
})
t.Run("with channels", func(t *testing.T) {
aChannel := make(chan Profile)
go func() {
aChannel <- Profile{21, "Berlin"}
aChannel <- Profile{28, "Beijing"}
close(aChannel)
}()
var got []string
want := []string{"Berlin", "Beijing"}
Walk(aChannel, func(input string) {
got = append(got, input)
})
if !reflect.DeepEqual(got, want) {
t.Errorf("got %v want %v", got, want)
}
})
}
func assertContains(t testing.TB, haystack []string, needle string) {