Skip to content

Add loops/dowhile.go #914

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/basic/loops/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@
| for_loop_two_variable.go | loops_two_variable | for ループで 2つの変数 を初期化してループさせるサンプルです |
| go122_loop_variable.go | loops_go122_loop_variable | Go 1.22 で導入された「ループ変数」の仕様変更についてのサンプルです. |
| go122_range_over_integer.go | loops_go122_range_over_integer | Go 1.22 で導入された range over integers ループ機能のサンプルです. |
| dowhile.go | loops_dowhile | Goで他の言語にある do-while と同様のことを行うサンプルです. |
59 changes: 59 additions & 0 deletions examples/basic/loops/dowhile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package loops

import (
"context"
"fmt"
"log"
"net"
"os"
"time"
)

// DoWhile は、Goで他の言語にある do-while と同様のことを行うサンプルです.
//
// Goにはループ制御が for しかないので、他の言語にある do-while は当然構文としては用意されていない。
// しかし、for で同じことは当然出来る。
func DoWhile() error {
type (
ctxKey struct{}
)
const (
retryMax = 2
)
var (
l = log.New(os.Stdout, "", log.Lmicroseconds)
i = 0
ctx = context.Background()

fn = func(ctx context.Context) {
// なんか処理している風
_, err := net.DialTimeout("tcp", ":12345", 10*time.Millisecond)
l.Printf("[%d] %v", ctx.Value(ctxKey{}).(int), err)
}
hr = func() {
fmt.Println("--------------------------------")
}
)

// do-while の代替 (1)
for {
fn(context.WithValue(ctx, ctxKey{}, i))
i++

// do-whileの条件判定の代わり
if i > retryMax {
break
}
}

hr()

// do-while の代替 (2)
i = 0
for ok := true; ok; ok = (i <= retryMax) {
fn(context.WithValue(ctx, ctxKey{}, i))
i++
}

return nil
}
1 change: 1 addition & 0 deletions examples/basic/loops/examples.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
m["loops_range_loop_tmpvalue_with_array"] = RangeLoopTmpValueWithArray
m["loops_go122_loop_variable"] = Go122LoopVariable
m["loops_go122_range_over_integer"] = Go122RangeOverInterger
m["loops_dowhile"] = DoWhile
}
Loading