How to replicate do while in go?

A do..while can more directly be emulated in Go with a for loop using a bool loop variable seeded with true.

for ok := true; ok; ok = EXPR { }

is more or less directly equivalent to

do { } while(EXPR)

So in your case:

var input int
for ok := true; ok; ok = (input != 2) {
    n, err := fmt.Scanln(&input)
    if n < 1 || err != nil {
        fmt.Println("invalid input")
        break
    }

    switch input {
    case 1:
        fmt.Println("hi")
    case 2:
        // Do nothing (we want to exit the loop)
        // In a real program this could be cleanup
    default:
        fmt.Println("def")
    }
}

Edit: Playground (with a dummied-out Stdin)

Though, admittedly, in this case it’s probably overall clearer to just explicitly call (labelled) break, return, or os.Exit in the loop.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)