Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I break out of an infinite loop in Golang [closed]

Tags:

for-loop

go

I'm making a program in Go for guessing a random number. I'm having issues with a for loop.

  1. I can't stop the for loop from continuously iterating.
  2. How do i break out of the loop once a condition is satisfied.

    for loop == true {
    
    //fmt.Println("read number", i, "/n")
    if i == ans {
        fmt.Println("well done")
    }
    if i != ans {
        fmt.Println("Nope")
        fmt.Scan(i)
    }
    
like image 842
MartinF Avatar asked Sep 28 '17 18:09

MartinF


1 Answers

You need to break out of the loop:

for {
    fmt.Scan(i)
    if i == ans {
        fmt.Println("well done")
        break
    }
    if i != ans {
        fmt.Println("Nope")
    }
}
like image 154
captncraig Avatar answered Oct 24 '22 09:10

captncraig