This is my first Go program. I would like to know what could be improved, what is done wrong, and anything else that I should know. The CSV contains 10 questions with the 10 answers separated by a comma. For example:
10+10,20
4+5,32
If you want the full context this is from gophercises which are some exercises to practice Go.
package main
import (
"encoding/csv"
"flag"
"fmt"
"math/rand"
"os"
"strings"
"time"
)
var points int
func main() {
fPtr := flag.String("csv", "problems.csv", "FileName in csv (question, answer)")
tPtr := flag.Int("time", 10, "Time in seconds")
sPtr := flag.Bool("shuffle", true, "shuffle your questions order")
flag.Parse()
questions := readCSV(*fPtr)
fmt.Print("Press enter to start you have ", *tPtr, " seconds")
fmt.Scanln()
askQuestions(&questions, *tPtr, *sPtr)
fmt.Println("You got ", points, " points")
}
func askQuestions(questions *[][]string, time int, s bool) {
go startTimer(time)
for _, i := range shuffle(s, len(*questions)) {
fmt.Println("Question ", (*questions)[i][0], ":")
var a string
fmt.Scan(&a)
a = strings.ToLower(strings.Trim(a, " "))
if a == (*questions)[i][1] {
points++
}
}
}
func shuffle(shuffle bool, sliceLen int) []int {
var r []int
for i := 0; i < sliceLen; i++ {
r = append(r, i)
}
if shuffle {
rand.Seed(time.Now().Unix())
rand.Shuffle(len(r), func(i, j int) {
r[i], r[j] = r[j], r[i]
})
}
return r
}
func readCSV(s string) (questions [][]string) {
f, err1 := os.Open(s)
records, err2 := csv.NewReader(f).ReadAll()
for err1 != nil || err2 != nil {
fmt.Println("Error: ", err1, err2)
fmt.Println("Please re-enter the name of the CSV file: ")
fmt.Scan(&s)
f, err1 = os.Open(s)
records, err2 = csv.NewReader(f).ReadAll()
}
return records
}
func startTimer(seconds int) {
time.Sleep(time.Duration(seconds) * time.Second)
fmt.Println("Time is up! You got ", points, " points")
os.Exit(0)
}