I just started developing a toy test cli program. I'm trying to implement a timer so that when the timer ends, the quiz is over.
This is my initial implementation.
func StartTimer(quizFinished chan bool, timer *time.Timer) { // Start timer <-timer.C fmt.Println("\nQuiz has ended") quizFinished <- true return } func askQuestions(timer *time.Timer, questions []string, answers []string) []string { var input string var userAnswers []string quizFinished := make(chan bool) fmt.Println("Starting Quiz...") go StartTimer(quizFinished, timer) for index, element := range questions { select { case <-quizFinished: fmt.Println("Quiz has ended") return userAnswers default: fmt.Printf("Question %d: %s? ", index+1, element) fmt.Scanln(&input) userAnswers = append(userAnswers, input) } } return userAnswers }
Edit implementation
package main import ( "bufio" "flag" "fmt" "log" "os" s "strings" "time" ) func readFileData(fileName string) (questions []string, answers []string) { file, err := os.Open(fileName) if err != nil { log.Fatalf("failed reading data from file: %v", err) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { questionAndAnswer := s.Split(scanner.Text(), ",") question, answer := questionAndAnswer[0], questionAndAnswer[1] questions = append(questions, question) answers = append(answers, answer) } return questions, answers } func askQuestions(timer *time.Timer, questions []string) []string { var input string var userAnswers []string = make([]string, 0, len(questions)) quizFinished := make(chan bool, 1) fmt.Println("Starting Quiz...") go func() { <-timer.C fmt.Println("\nquiz over...") quizFinished <- true }() for index, element := range questions { fmt.Printf("Question %d: %s? ", index+1, element) answerCh := make(chan string, 1) go func() { fmt.Scanln(&input) answerCh <- input }() select { case <-quizFinished: return userAnswers case answer := <-answerCh: userAnswers = append(userAnswers, answer) } } return userAnswers } func main() { fileNamePtr := flag.String("filename", "problems.csv", "Specify a file name to read in") quizTimePtr := flag.Int("time", 5, "Specify how long the quiz should take") flag.Parse() timer := time.NewTimer(time.Duration(*quizTimePtr) * time.Second) questions, answers := readFileData(*fileNamePtr) // var userAnswers = askQuestions(timer, questions, answers) var userAnswers = askQuestions(timer, questions) correctAnswers := 0 incorrectAnswers := 0 for i := 0; i < len(answers); i++ { if userAnswers[i] == answers[i] { correctAnswers++ } else { incorrectAnswers++ } } grade := float32(correctAnswers) / float32(len((questions))) fmt.Printf("Total Questions: %d \n", len(questions)) fmt.Printf("Total Correct Answers: %d \n", correctAnswers) fmt.Printf("Total Incorrect Answers: %d \n", incorrectAnswers) fmt.Printf("Grade: %.0f%% \n", grade*100) }
I keep getting the following output and error:
Starting Quiz... Question 1: 5+5? 10 Question 2: 1+1? Quiz has ended 2 Returning from quiz... panic: runtime error: index out of range [2] with length 2 goroutine 1 [running]:
I don't understand channels and goroutines well enough yet to understand what's going on. The expected behavior is that when the timer stops, it prints "Quiz ended" and sends a value to the quizFinished channel, which is read in the select statement. Another problem I have is that Scanln will wait for user input after the quiz is over. Any help would be greatly appreciated!
Correct answer
When you call the Scanln
function in the main goroutine, it pauses and waits for user input. Even if your timer completes in another Goroutine and tries to notify the main Goroutine, the main Goroutine will not respond because it is blocked by the "Scanner".
That's why even after the timer expires, Scanln
is still waiting for user input.
package main import ( "fmt" "time" ) func askQuestions(timer *time.Timer, questions []string) []string { var input string var userAnswers []string quizFinished := make(chan bool, 1) fmt.Println("start quiz...") go func() { <-timer.C fmt.Println("\nquiz over...") quizFinished <- true }() for index, element := range questions { fmt.Printf("question %d: %s? ", index+1, element) answerCh := make(chan string, 1) go func() { fmt.Scanln(&input) answerCh <- input }() select { case <-quizFinished: fmt.Println("exit quiz...") return userAnswers case answer := <-answerCh: userAnswers = append(userAnswers, answer) } } return userAnswers } func main() { timer := time.NewTimer(10 * time.Second) questions := []string{"5+5", "1+1", "8+3"} responses := askQuestions(timer, questions) fmt.Println("answer:", responses) }
The above is the detailed content of How to return from function when timer completes in go?. For more information, please follow other related articles on the PHP Chinese website!

GoroutinesarefunctionsormethodsthatrunconcurrentlyinGo,enablingefficientandlightweightconcurrency.1)TheyaremanagedbyGo'sruntimeusingmultiplexing,allowingthousandstorunonfewerOSthreads.2)Goroutinesimproveperformancethrougheasytaskparallelizationandeff

ThepurposeoftheinitfunctioninGoistoinitializevariables,setupconfigurations,orperformnecessarysetupbeforethemainfunctionexecutes.Useinitby:1)Placingitinyourcodetorunautomaticallybeforemain,2)Keepingitshortandfocusedonsimpletasks,3)Consideringusingexpl

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

Use the recover() function in Go to recover from panic. The specific methods are: 1) Use recover() to capture panic in the defer function to avoid program crashes; 2) Record detailed error information for debugging; 3) Decide whether to resume program execution based on the specific situation; 4) Use with caution to avoid affecting performance.

The article discusses using Go's "strings" package for string manipulation, detailing common functions and best practices to enhance efficiency and handle Unicode effectively.

The article details using Go's "crypto" package for cryptographic operations, discussing key generation, management, and best practices for secure implementation.Character count: 159

The article details the use of Go's "time" package for handling dates, times, and time zones, including getting current time, creating specific times, parsing strings, and measuring elapsed time.

Article discusses using Go's "reflect" package for variable inspection and modification, highlighting methods and performance considerations.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
