There is list of questions. I show question one after one to user and wait for user`s answer. Every question should be answered in some seconds( for example 5 second for question). If question is answered right and in time, then user get some points. My code is looks like:
for i := 0; i < len(questions); i++ {
fmt.Println(questions[i].Text)
ans := make(chan int)
go func() {
fmt.Print("Enter answer ")
var u int
fmt.Scanf("%d
", &u)
ans <- u
}()
select {
case userAnswer := <-ans:
if userAnswer == questions[i].Answer {
points++
}
case <-time.After(5 * time.Second):
fmt.Println("
Time is over!")
}
}
Problem is next: if user don`t answer to question, then he get message "Time is over", as expected. But next answer will not be processed, and user should type it again. It looks like next output:
question with answer 1
Enter answer: 1
1 is right answer
question with answer 2
Enter answer: 2
2 is right answer
question with answer 3
Enter answer:
Time is over!
question with answer 4
Enter answer: 4
4
4 is right answer
question with answer 5
Enter answer: 5
5 is right answer
User did not answer to question #3, so he need to answer to question #4 twice. I understand that problem is because goroutines and channels. But I don`t understand, why was not value, that was read from stdin after timeout, sent to or get from channel "ans".
Why value from channel was not properly received after timeout? How I can rewrite code, so user don`t need to repeat input twice after timeout to previous question?
Sorry for bad english and thanks for help.