You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang命令行测验程序异常:后续题目成对出现且无法接收答案

Golang命令行测验程序问题排查

我是Golang新手,跟着在线教程开发一个简单的命令行测验程序,但本地运行时出现异常:第一题之后,剩余题目会成对出现,且无法接收每道题的答案。

程序预期流程:

  • 从本地CSV文件读取题目
  • 逐题打印并接收用户答案
  • 统计正确答案数量并在最后展示

CSV文件内容:

70+22,92
63+67,130
91+72,163
74+61,135
81+6,87

完整程序代码:

package main

import (
    "encoding/csv"
    "flag"
    "fmt"
    "os"
    "time"
)

func main() {
    // 1. input the name of the file
    fName := flag.String("f", "quiz.csv", "path of csv file")
    // 2. set the duration of timer
    timer := flag.Int("t", 30, "timer for the quiz")
    flag.Parse()
    // 3. pull the problems from the file  (calling our problem puller)
    problems, err := problemPuller(*fName)
    // 4. handle the error
    if err != nil {
        exit(fmt.Sprintf("something went wrong: %s", err.Error()))
    }
    // 5. create a variable to count our correct answers
    correctAns := 0
    // 6. using the duration of the timer, we want to initialize the timer
    tObj := time.NewTimer(time.Duration(*timer) * time.Second)
    ansC := make(chan string)
    // 7. loop through the problems, print the questions, we'll accept the answers
    problemLoop: 
        for i, p := range problems {
            var answer string
            fmt.Printf("Problem %d: %s =", i+1, p.question)

            go func() {
                fmt.Scanf("%s", &answer)
                ansC <- answer
            }()
            select {
                case <- tObj.C:
                    fmt.Println()
                    break problemLoop
                case iAns := <- ansC:
                    if iAns == p.answer {
                        correctAns++
                    }
                    if i == len(problems)-1 {
                        close(ansC)
                    }
            }
        }
    // 8. calculate and print out the result
    fmt.Printf("Your result is %d out of %d\n", correctAns, len(problems))
    fmt.Printf("Press enter to exit")
    <- ansC
}

func problemPuller(fileName string) ([]problem, error) {
    // read all the problems from the quiz.csv

    // 1. open the file
    if fObj, err := os.Open(fileName); err == nil {
        // 2. we will create new reader
        csvR := csv.NewReader(fObj)
        // 3. it will need to read the file
        if cLines, err := csvR.ReadAll(); err == nil {
            // 4. call the parseProblem function
            return parseProblem(cLines), nil
        } else {
            return nil, fmt.Errorf("error in reading data in csv from %s file; %s", fileName, err.Error())
        }
    } else {
            return nil, fmt.Errorf("error in opening the file %s file; %s", fileName, err.Error())
    }
}

func parseProblem(lines [][]string) []problem {
    // go over the lines and parse them based on the problem struct
    r := make([] problem, len(lines))
    for i := 0; i < len(lines); i++ {
        r[i] = problem {
            question: lines[i][0],
            answer: lines[i][1],
        }
    }
    return r
}

type problem struct {
    question string
    answer   string
}

func exit(msg string) {
    fmt.Println(msg)
    os.Exit(1)
}

错误原因分析

核心问题是循环中goroutine对变量的引用共享:

  1. 循环内的var answer string是每次迭代复用的变量,goroutine捕获的是该变量的内存地址,导致多个goroutine共享同一个变量。当循环快速推进时,后续goroutine会覆盖之前的输入,同时多个fmt.Scanf会争抢标准输入,造成题目“成对出现”的现象。
  2. 循环结束后最后的<- ansC会等待一个不存在的输入,若所有题目完成,通道关闭后该操作会直接返回空字符串,但逻辑上属于多余的阻塞。

修复后的代码

package main

import (
    "encoding/csv"
    "flag"
    "fmt"
    "os"
    "time"
)

func main() {
    fName := flag.String("f", "quiz.csv", "path of csv file")
    timer := flag.Int("t", 30, "timer for the quiz")
    flag.Parse()

    problems, err := problemPuller(*fName)
    if err != nil {
        exit(fmt.Sprintf("something went wrong: %s", err.Error()))
    }

    correctAns := 0
    tObj := time.NewTimer(time.Duration(*timer) * time.Second)
    ansC := make(chan string)

    problemLoop:
        for i, p := range problems {
            fmt.Printf("Problem %d: %s =", i+1, p.question)

            // 每个goroutine内部声明独立的answer变量,避免引用共享
            go func() {
                var answer string
                fmt.Scanf("%s", &answer)
                ansC <- answer
            }()

            select {
                case <- tObj.C:
                    fmt.Println()
                    break problemLoop
                case iAns := <- ansC:
                    if iAns == p.answer {
                        correctAns++
                    }
            }
        }
    // 停止定时器,避免goroutine泄漏
    if !tObj.Stop() {
        <-tObj.C
    }
    fmt.Printf("Your result is %d out of %d\n", correctAns, len(problems))
    fmt.Println("Press enter to exit")
    // 直接读取输入完成退出,不再依赖之前的答案通道
    var dummy string
    fmt.Scanln(&dummy)
}

// 以下函数保持不变
func problemPuller(fileName string) ([]problem, error) {
    if fObj, err := os.Open(fileName); err == nil {
        csvR := csv.NewReader(fObj)
        if cLines, err := csvR.ReadAll(); err == nil {
            return parseProblem(cLines), nil
        } else {
            return nil, fmt.Errorf("error in reading data in csv from %s file; %s", fileName, err.Error())
        }
    } else {
            return nil, fmt.Errorf("error in opening the file %s file; %s", fileName, err.Error())
    }
}

func parseProblem(lines [][]string) []problem {
    r := make([] problem, len(lines))
    for i := 0; i < len(lines); i++ {
        r[i] = problem {
            question: lines[i][0],
            answer: lines[i][1],
        }
    }
    return r
}

type problem struct {
    question string
    answer   string
}

func exit(msg string) {
    fmt.Println(msg)
    os.Exit(1)
}

关键修复点

  • 将var answer string移到goroutine内部,每个goroutine拥有独立的变量,彻底解决循环变量引用共享的问题。
  • 移除不必要的通道关闭操作,循环结束后停止定时器防止goroutine泄漏。
  • 最后的退出输入改用直接读取,不再依赖之前的答案通道,避免多余阻塞。

内容的提问来源于stack exchange,提问作者coderfromhell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 11:57:47