Am a beginner of GoLang here is a sample code from a tutorial.
func main() {
for {
var name string
var email string
var userTickets uint
// ask user for info
fmt.Println("Input your Name please")
fmt.Scan(&name)
fmt.Println("Input your Email please")
fmt.Scan(&email)
// ask user for number of tickets
fmt.Println("Input number of ticket")
if _, err := fmt.Scanln(&userTickets); err != nil {
fmt.Println(err)
}
}
}
Here is an interesting thing I found: if I entered "-1" in "Input number of ticket". It will throw an error since userTickets is uint. With that err it will also put an "enter/next line" for "Input your Name please" in the next loop. The result would look like this
Input your Name please
Test
Input your Email please
Test
Input number of tickect
-1
expected integer
Input your Name please <= this input is skipped
Input your Email please
So just wondering why this heppened? How can I resolve that (without changing type from uint to int)?
-1
then-
causes thefmt.Scanln(&userTicket)
to exit with error, the nextfmt.Scan(&name)
statement doesn't block because it is fed the remaining input, i.e.1
.