How to pass keyboard input to a running program?

Written by
Link to Post by 

I am a newbie to Go and have been following tutorials and a book to learn. Now, here is a scenario which I am trying but have not been successful with the Go channel feature.

Suppose you have a long running loop

func longLoop(text string){ for range time.Tick(time.Second * 1) { //long running for loop fmt.Println("Results of long calculation are:" + someValue) //keep listening to channel for user's keyboard entered value if(len(text)>0 ){ fmt.Println("Hey you typed:" + text) } } } func main() { go longLoop("") go readKeyBoard() time.Sleep(time.Second * 10000000) } 

Now I want to type some text, maybe just a word while this program is running and use that keyboard input. I know from my learning that I can capture the keyboard input as follows

func readKeyboard() { scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { fmt.Println(scanner.Text()) //put the scanner.Text() value on a channel } } 

I tried passing in a channel for strings, to both routines and setting the keyboard input value to the channel. Somehow, I am unable to get it to work. The idea was that whatever is typed by keyboard will be put on a channel as input. The same channel will be read in the long loop function and used.

I thought that the main function can launch both go routines and a common channel would be the data carrier between the two. Somehow, all the examples shown do not address what I am trying to do.

I am a newbie to Go and request your help.

submitted by /u/naturalizedcitizen
[link] [comments]

Article Tags:
· ·
Article Categories:

Leave a Reply