You've probably written a program and once wanted to create a standard input with a time limit. By the way, I don't. Since it was easily realized with Go, I will write a memo. It's for me someday.
The method is very simple, just create a subroutine that receives standard input and receive the input text on the channel.
in := make(chan string, 1)
go func() {
sc := bufio.NewScanner(os.Stdin)
sc.Scan()
in <- sc.Text()
}()
This can be easily achieved by combining the above channel with time.NewTimer
or time.NewTicker
.
timer := time.NewTimer(time.Second * 10)
select {
case text := <-in:
//Processing using input
case <-timer.C:
//Processing at the time of timeout
}
This is a sample made by the above method. You can get a feel for it by running it locally.
package main
import (
"bufio"
"fmt"
"os"
"time"
)
func main() {
in := make(chan string, 1)
go func() {
sc := bufio.NewScanner(os.Stdin)
sc.Scan()
in <- sc.Text()
}()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
fmt.Println("The time limit is 5 seconds. Enter the author of the boy")
for i := 0; i < 5; i++ {
select {
case text := <-in:
if text == "Natsume Soseki" {
fmt.Printf("It's amazing to be able to enter\n")
} else {
fmt.Printf("I'm wrong\n%s\n", text)
}
i = 5
case <-ticker.C:
switch i {
case 0:
fmt.Println("There is a time limit, so be quick")
case 1:
fmt.Println("quickly quickly")
case 2:
fmt.Println("Do you think it's in the way?")
case 3:
fmt.Println("I agree with you")
case 4:
fmt.Println("Game over(Lol)")
}
}
}
}
It was easy, but when will you use it?
Recommended Posts