Skip to content

Commit 56c1d4c

Browse files
authored
Merge pull request #713 from devlights:add-bytes-repeat-example
Add examples/byteop/using_repeat.go
2 parents 386f62e + 6ce3167 commit 56c1d4c

File tree

3 files changed

+53
-1
lines changed

3 files changed

+53
-1
lines changed

examples/basic/byteop/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@
55
|file|example name|note|
66
|----|------------|----|
77
|reader\_from\_byteslice.go|byteop\_reader\_from\_byteslice|[]byte から io.Reader を生成するサンプルです.|
8-
8+
|using\_repeat.go|byteop\_using\_repeat|bytes.Repeat() のサンプルです|

examples/basic/byteop/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,5 @@ func NewRegister() mapping.Register {
1515
func (r *register) Regist(m mapping.ExampleMapping) {
1616
m["byteop_reader_from_byteslice"] = ReaderFromByteSlice
1717
m["byteop_cut_prefix_suffix"] = CutPrefixSuffix
18+
m["byteop_using_repeat"] = UsingRepeat
1819
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package byteop
2+
3+
import (
4+
"bytes"
5+
6+
"github.com/devlights/gomy/output"
7+
)
8+
9+
// UsingRepeat は、bytes.Repeat() のサンプルです.
10+
//
11+
// # REFERENCES
12+
// - https://pkg.go.dev/bytes@go1.21.5#Repeat
13+
func UsingRepeat() error {
14+
//
15+
// インデックス付きの for ループを書くのが面倒なときに結構便利
16+
//
17+
for i, v := range bytes.Repeat([]byte{1}, 10) {
18+
output.Stdoutl("[i, v]", i, v)
19+
}
20+
21+
output.StdoutHr()
22+
23+
//
24+
// 所定のスライスを繰り返して処理したいとき
25+
//
26+
var (
27+
ch = make(chan int)
28+
done = make(chan struct{})
29+
)
30+
31+
go func(ch chan<- int) {
32+
defer close(ch)
33+
34+
for _, v := range bytes.Repeat([]byte{1, 2, 3, 4, 5}, 3) {
35+
i := int(v)
36+
ch <- i * i
37+
}
38+
}(ch)
39+
40+
go func(done chan<- struct{}, ch <-chan int) {
41+
defer close(done)
42+
43+
for v := range ch {
44+
output.Stdoutl("[v]", v)
45+
}
46+
}(done, ch)
47+
48+
<-done
49+
50+
return nil
51+
}

0 commit comments

Comments
 (0)