I'm new with Go syntax, just trying to pass an error if the user did not input anything...
[EDIT] I would like the following function to stop running if the user did not input anything, and print a log. My if required && answer == ""
statement doesn't seem to work as "You must enter a value." does not log when the user does not input anything.
func QAR(q string, r string, required bool) string {
reader := bufio.NewReader(os.Stdin)
// Print the question
fmt.Printf(q)
answer, _ := reader.ReadString('
')
// If the answer is empty, return a log
if required && answer == "" {
log.Fatal("You must enter a value.")
// Can I just use return to block it?
return
}
// Print the response with the answer
if r != "" {
fmt.Println(r, answer)
}
return answer
}
The typical pattern in go is to return multiple values, the last of which is an error, if one occurred. So your function signature could look like this:
func QAR(q string, r string, required bool) (string, error)
And the return statements like this:
return "", fmt.Errorf("user provided no input")
// ...
return answer, nil
[EDIT]
Note that bufio.Reader.ReadString(...)
includes the delimiter, so you probably need to check if answer == " "
.