Skip to content

Instantly share code, notes, and snippets.

@Ozoniuss
Created September 30, 2023 11:21
Show Gist options
  • Save Ozoniuss/4aa24e917e4581c6dd9ac4b951407d11 to your computer and use it in GitHub Desktop.
Save Ozoniuss/4aa24e917e4581c6dd9ac4b951407d11 to your computer and use it in GitHub Desktop.
2-prompter, new scanner in each function
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
// scanStringUntilValid is a helper provided to get a string input from the
// terminal. It doesn't do any additional logic to simply retrieving the user
// input; it is only provided for consistency.
func scanStringUntilValid(prefix string) string {
fmt.Print(prefix)
s := bufio.NewScanner(os.Stdin)
s.Scan()
return s.Text()
}
// scanIntUntilValid is a helper provided to get a float input from the terminal.
// It will prompt the user for a value until the value is a valid floating
// point number.
func scanFloatUntilValid(prefix string) float64 {
var valfloat float64
var err error
s := bufio.NewScanner(os.Stdin)
for {
fmt.Print(prefix)
s.Scan()
val := s.Text()
if valfloat, err = strconv.ParseFloat(val, 64); err != nil {
fmt.Println("Invalid number, please try again.")
continue
}
return float64(valfloat)
}
}
type Debt struct {
Person string
Amount float64
Currency string
Details string
}
func CreateDebtPrompter(header string) Debt {
if header != "" {
fmt.Println(header)
}
debt := Debt{}
debt.Person = scanStringUntilValid("person: ")
debt.Amount = scanFloatUntilValid("amount: ")
debt.Currency = scanStringUntilValid("currency: ")
debt.Details = scanStringUntilValid("details: ")
return debt
}
func main() {
debt := CreateDebtPrompter("")
fmt.Println("debt created: %s", debt)
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment