Browse Source

Initial commit

master
joop 2 months ago
commit
2f645ce8e6
  1. BIN
      example/example
  2. 15
      example/example.go
  3. 3
      go.mod
  4. 40
      prompt.go

BIN
example/example

Binary file not shown.

15
example/example.go

@ -0,0 +1,15 @@ @@ -0,0 +1,15 @@
package main
import (
"fmt"
"git.kiefte.eu/lapingvino/prompt"
)
func main() {
fmt.Print("Enter a string: ")
s := prompt.MustRead[string]()
fmt.Print("Now enter a complex number: ")
c := prompt.MustRead[complex128]()
fmt.Println(s, c)
}

3
go.mod

@ -0,0 +1,3 @@ @@ -0,0 +1,3 @@
module git.kiefte.eu/lapingvino/prompt
go 1.18

40
prompt.go

@ -0,0 +1,40 @@ @@ -0,0 +1,40 @@
package prompt
import (
"bufio"
"fmt"
"os"
)
type Prompter interface {
Prompt(string)
}
func Read[T any]() (out T, err error) {
nilv := out
b := bufio.NewReader(os.Stdin)
s, err := b.ReadString('\n')
if err != nil {
return nilv, err
}
switch o := any(&out).(type) {
case *string:
*o = s[:len(s)-1]
case *Prompter:
(*o).Prompt(s)
default:
_, err = fmt.Sscan(s, &out)
if err != nil {
return nilv, err
}
}
return out, nil
}
func MustRead[T any]() T {
out, err := Read[T]()
if err != nil {
panic("Error during read: "+err.Error())
}
return out
}
Loading…
Cancel
Save