Initial commit
commit
2f645ce8e6
Binary file not shown.
@ -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)
|
||||
}
|
@ -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…
Reference in New Issue