search
HomeBackend DevelopmentGolangHow to return from function when timer completes in go?

当 go 中计时器完成时如何从函数返回?

Question content

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!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
Understanding Goroutines: A Deep Dive into Go's ConcurrencyUnderstanding Goroutines: A Deep Dive into Go's ConcurrencyMay 01, 2025 am 12:18 AM

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

Understanding the init Function in Go: Purpose and UsageUnderstanding the init Function in Go: Purpose and UsageMay 01, 2025 am 12:16 AM

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

Understanding Go Interfaces: A Comprehensive GuideUnderstanding Go Interfaces: A Comprehensive GuideMay 01, 2025 am 12:13 AM

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

Recovering from Panics in Go: When and How to Use recover()Recovering from Panics in Go: When and How to Use recover()May 01, 2025 am 12:04 AM

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.

How do you use the "strings" package to manipulate strings in Go?How do you use the "strings" package to manipulate strings in Go?Apr 30, 2025 pm 02:34 PM

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

How do you use the "crypto" package to perform cryptographic operations in Go?How do you use the "crypto" package to perform cryptographic operations in Go?Apr 30, 2025 pm 02:33 PM

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

How do you use the "time" package to handle dates and times in Go?How do you use the "time" package to handle dates and times in Go?Apr 30, 2025 pm 02:32 PM

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.

How do you use the "reflect" package to inspect the type and value of a variable in Go?How do you use the "reflect" package to inspect the type and value of a variable in Go?Apr 30, 2025 pm 02:29 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

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

Dreamweaver CS6

Visual web development tools

mPDF

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),