【发布时间】:2020-05-18 15:37:36
【问题描述】:
刚接触 golang 和一般编程。我目前正在为学习任务编写一个小测验程序,但遇到了教程未解决的问题,因为我有教程中未包含的功能。
代码如下:
func runQuestions(randomize bool) int {
tempqSlice := qSlice //Create temporary set of questions (Don't touch original)
if randomize { //If user has chosen to randomize the question order
tempqSlice = shuffle(tempqSlice) //Randomize
}
var runningscore int
userinputchan := make(chan string) //Create return channel for user input
go getInput(userinputchan) //Constantly wait for user input
for num, question := range tempqSlice { //Iterate over each question
fmt.Printf("Question %v:\t%v\n\t", num+1, question.GetQuestion())
select {
case <-time.After(5 * time.Second): //
fmt.Println("-time up! next question-")
continue
case input := <-userinputchan:
if question.GetAnswer() == input { //If the answer is correct
runningscore++
continue //Continue to next question
}
}
}
return runningscore
}
func getInput(returnchan chan<- string) {
for {
reader := bufio.NewReader(os.Stdin) //Create reader
input, _ := reader.ReadString('\n') //Read from
returnchan <- strings.TrimSpace(input) //Trim the input and send it
}
}
因为问题的规范要求每个问题都有时间限制,所以我设置了一个“无尽的 for loop goroutine”运行,等待用户输入,然后在给出时发送。我的问题很简单:我想在测验结束后停止读者寻找输入,但由于 'reader.ReadString('/n')' 已经在等待输入,我不知道如何。
【问题讨论】:
-
你不能。直到程序退出为止。
-
对于程序不同部分的输入,我是否可以简单地将“输入循环”移动到靠近程序顶部并将其通道传递给任何其他需要输入的函数?
-
根据回答的问题数量和问题的长度创建一个案例。
case amountOfQuestionsAnswered == len(questions): exit